Open In App

Queries for counts of array values in a given range

Last Updated : 20 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an unsorted array of integers and a set of m queries, where each query consists of two integers x and y, the task is to determine the number of elements in the array that lie within the range [x, y] (inclusive) for each query.

Examples: 

Input: arr = [1, 3, 4, 9, 10, 3], queries = [[1, 4], [9, 12]]
Output: 4 2
Explanation:
The numbers are: 1 3 3 4 for first query
The numbers are: 9 10 for second query

Input: arr = [5, 5, 8, 10, 12], queries = [[5, 10], [1, 3]]
Output: 4 0
Explanation:
For the query [5, 10], the numbers are: 5, 5, 8, 10
For the query [1, 3], there are no numbers in the range

[Naive Approach] Using Brute Force Method – O(n * m) time and O(1) space

The idea is to traverse the entire array for each query and count the number of elements that lie within the given range [x, y]. For every query, iterate through all elements of the array, check if the current element satisfies the condition x ≤ element ≤ y, and increment the count if it does.

C++
// C++ program to count number of elements
// with values in given range.
#include <bits/stdc++.h>
using namespace std;

// function to count elements within given range
vector<int> countInRange(vector<int> &arr, 
vector<vector<int>> &queries) {
    
    int n = arr.size(), m = queries.size();
    
    vector<int> ans(m);
    
    // For each query,
    for (int i=0; i<m; i++) {
        int cnt = 0;
        int x = queries[i][0], y = queries[i][1];
        
        // Count all elements in range [x, y]
        for (int j=0; j<n; j++) {
            if (arr[j]>=x && arr[j]<=y) cnt++;
        }
        
        ans[i] = cnt;
    }
    
    return ans;
}

int main() {
    vector<int> arr = { 1, 3, 4, 9, 10, 3 };
    vector<vector<int>> queries = {{1, 4}, {9, 12}};

    vector<int> ans = countInRange(arr, queries);
    
    for (auto val: ans) {
        cout << val << " ";
    }
    cout << endl;
    
    return 0;
}
Java
// Java program to count number of elements
// with values in given range.

class GfG {
    
    // function to count elements within given range
    static int[] countInRange(int[] arr, int[][] queries) {
        int n = arr.length, m = queries.length;
        int[] ans = new int[m];

        // For each query,
        for (int i = 0; i < m; i++) {
            int cnt = 0;
            int x = queries[i][0], y = queries[i][1];

            // Count all elements in range [x, y]
            for (int j = 0; j < n; j++) {
                if (arr[j] >= x && arr[j] <= y) cnt++;
            }

            ans[i] = cnt;
        }

        return ans;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 4, 9, 10, 3};
        int[][] queries = {{1, 4}, {9, 12}};

        int[] ans = countInRange(arr, queries);

        for (int val : ans) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}
Python
# Python program to count number of elements
# with values in given range.

# function to count elements within given range
def countInRange(arr, queries):
    n = len(arr)
    m = len(queries)
    
    ans = [0] * m

    # For each query,
    for i in range(m):
        cnt = 0
        x, y = queries[i]

        # Count all elements in range [x, y]
        for j in range(n):
            if arr[j] >= x and arr[j] <= y:
                cnt += 1

        ans[i] = cnt

    return ans

if __name__ == "__main__":
    arr = [1, 3, 4, 9, 10, 3]
    queries = [[1, 4], [9, 12]]

    ans = countInRange(arr, queries)

    print(" ".join(map(str, ans)))
C#
// C# program to count number of elements
// with values in given range.

using System;

class GfG {
    
    // function to count elements within given range
    static int[] countInRange(int[] arr, int[][] queries) {
        int n = arr.Length, m = queries.Length;
        int[] ans = new int[m];

        // For each query,
        for (int i = 0; i < m; i++) {
            int cnt = 0;
            int x = queries[i][0], y = queries[i][1];

            // Count all elements in range [x, y]
            for (int j = 0; j < n; j++) {
                if (arr[j] >= x && arr[j] <= y) cnt++;
            }

            ans[i] = cnt;
        }

        return ans;
    }

    static void Main(string[] args) {
        int[] arr = {1, 3, 4, 9, 10, 3};
        int[][] queries = { new int[] {1, 4}, new int[] {9, 12} };

        int[] ans = countInRange(arr, queries);

        Console.WriteLine(string.Join(" ", ans));
    }
}
JavaScript
// JavaScript program to count number of elements
// with values in given range.

// function to count elements within given range
function countInRange(arr, queries) {
    let n = arr.length, m = queries.length;
    let ans = new Array(m).fill(0);

    // For each query,
    for (let i = 0; i < m; i++) {
        let cnt = 0;
        let x = queries[i][0], y = queries[i][1];

        // Count all elements in range [x, y]
        for (let j = 0; j < n; j++) {
            if (arr[j] >= x && arr[j] <= y) cnt++;
        }

        ans[i] = cnt;
    }

    return ans;
}

let arr = [1, 3, 4, 9, 10, 3];
let queries = [[1, 4], [9, 12]];

let ans = countInRange(arr, queries);

console.log(ans.join(" "));

Output
4 2 

[Better Approach] Using Segment Tree

A segment tree is a binary tree where each node represents a segment of the array. The leaves of the tree represent the individual elements of the array, and the parent nodes represent the union of their children.

To answer a query [i, j], we traverse the segment tree from the root to the leaves, keeping track of the segments that contain i and j. At each node, we use the precomputed values to compute the number of elements in the segment that are less than or equal to x. We merge the values for the left and right child nodes and return the final result.

C++
#include <bits/stdc++.h>
using namespace std;

// Segment Tree class
struct SegmentTree {
	vector<int> tree;
	int low, high;
	
	SegmentTree(int n) { tree.resize(4 * n); }

	// Build the tree with array elements
	void build(vector<int>& arr, int v, int tl, int tr) {
		if (tl == tr) {
			tree[v] = (arr[tl] >= low && arr[tl] <= high) ? 1 : 0;
		} else {
			int tm = (tl + tr) / 2;
			build(arr, v * 2, tl, tm);
			build(arr, v * 2 + 1, tm + 1, tr);
			
			// Sum of left and right child
			tree[v] = tree[v * 2] + tree[v * 2 + 1];
		}
	}

	// Query the tree for given range
	int query(int v, int tl, int tr, int l, int r) {
	    
	    // No elements in the range
		if (l > r) return 0;
		
		// Exact match
		if (l == tl && r == tr) return tree[v]; 
		
		// Sum of left and right child queries
		int tm = (tl + tr) / 2;
		return query(v * 2, tl, tm, l, min(r, tm)) +
		       query(v * 2 + 1, tm + 1, tr, max(l, tm + 1), r);
	}

	// Update tree at index i with given value
	void update(int v, int tl, int tr, int i, int val) {
		if (tl == tr) {
		    
			// Update leaf node based on range condition
			tree[v] = (val >= low && val <= high) ? 1 : 0;
		} else {
			int tm = (tl + tr) / 2;
			if (i <= tm) update(v * 2, tl, tm, i, val);
			else update(v * 2 + 1, tm + 1, tr, i, val);
			
			// Recalculate sum of left and right child
			tree[v] = tree[v * 2] + tree[v * 2 + 1];
		}
	}

	// Set range for the tree
	void setRange(int l, int h) { low = l, high = h; }
};

// Function to count elements within given range
int countInRange(const vector<int>& arr, int x, int y) {
	int n = arr.size();
	SegmentTree st(n);
	st.setRange(x, y);
	st.build(arr, 1, 0, n - 1);
	return st.query(1, 0, n - 1, 0, n - 1);
}

// Driver function
int main() {
	vector<int> arr = {1, 3, 4, 9, 10, 3};

	// Answer queries
	int i = 1
Java
import java.util.*;

class SegmentTree {
	private List<Integer> tree;
	private int low, high;

	SegmentTree(int n)
	{
		tree = new ArrayList<>(4 * n);
		for (int i = 0; i < 4 * n; i++) {
			tree.add(0);
		}
	}

	// build the tree with array elements
	void build(int[] arr, int v, int tl, int tr)
	{
		if (tl == tr) {
			tree.set(v, (arr[tl] >= low && arr[tl] <= high)
							? 1
							: 0);
		}
		else {
			int tm = (tl + tr) / 2;
			build(arr, v * 2, tl, tm);
			build(arr, v * 2 + 1, tm + 1, tr);
			tree.set(v,
					tree.get(v * 2) + tree.get(v * 2 + 1));
		}
	}

	// query the tree for given range
	int query(int v, int tl, int tr, int l, int r)
	{
		if (l > r) {
			return 0;
		}
		if (l == tl && r == tr) {
			return tree.get(v);
		}
		int tm = (tl + tr) / 2;
		return query(v * 2, tl, tm, l, Math.min(r, tm))
			+ query(v * 2 + 1, tm + 1, tr,
					Math.max(l, tm + 1), r);
	}

	// update tree at index i with given value
	void update(int v, int tl, int tr, int i, int val)
	{
		if (tl == tr) {
			tree.set(v,
					(val >= low && val <= high) ? 1 : 0);
		}
		else {
			int tm = (tl + tr) / 2;
			if (i <= tm) {
				update(v * 2, tl, tm, i, val);
			}
			else {
				update(v * 2 + 1, tm + 1, tr, i, val);
			}
			tree.set(v,
					tree.get(v * 2) + tree.get(v * 2 + 1));
		}
	}

	// set range for the tree
	void setRange(int l, int h)
	{
		low = l;
		high = h;
	}
}

public class GFG {
	// function to count elements within given range
	static int countInRange(int[] arr, int n, int x, int y)
	{
		SegmentTree st = new SegmentTree(n);
		st.setRange(x, y);
		st.build(arr, 1, 0, n - 1);
		return st.query(1, 0, n - 1, 0, n - 1);
	}

	// driver function
	public static void main(String[] args)
	{
		int[] arr = { 1, 3, 4, 9, 10, 3 };
		int n = arr.length;

		// Answer queries
		int i = 1, j = 4;
		System.out.println(countInRange(arr, n, i, j));

		i = 9;
		j = 12;
		System.out.println(countInRange(arr, n, i, j));
	}
}
Python
# Python program to count number of elements
# with values in given range using segment tree

# Segment Tree class


class SegmentTree:
	def __init__(self, n):
		self.tree = [0] * (4*n)

	# build the tree with array elements
	def build(self, arr, v, tl, tr, low, high):
		if tl == tr:
			self.tree[v] = 1 if low <= arr[tl] <= high else 0
		else:
			tm = (tl + tr) // 2
			self.build(arr, v*2, tl, tm, low, high)
			self.build(arr, v*2+1, tm+1, tr, low, high)
			self.tree[v] = self.tree[v*2] + self.tree[v*2+1]

	# query the tree for given range
	def query(self, v, tl, tr, l, r):
		if l > r:
			return 0
		if l == tl and r == tr:
			return self.tree[v]
		tm = (tl + tr) // 2
		return self.query(v*2, tl, tm, l, min(r, tm)) + \
			self.query(v*2+1, tm+1, tr, max(l, tm+1), r)

	# update tree at index i with given value
	def update(self, v, tl, tr, i, val, low, high):
		if tl == tr:
			self.tree[v] = 1 if low <= val <= high else 0
		else:
			tm = (tl + tr) // 2
			if i <= tm:
				self.update(v*2, tl, tm, i, val, low, high)
			else:
				self.update(v*2+1, tm+1, tr, i, val, low, high)
			self.tree[v] = self.tree[v*2] + self.tree[v*2+1]

	# set range for the tree
	def set_range(self, low, high):
		self.low = low
		self.high = high

# function to count elements within given range


def count_in_range(arr, n, x, y):
	st = SegmentTree(n)
	st.set_range(x, y)
	st.build(arr, 1, 0, n-1, x, y)
	return st.query(1, 0, n-1, 0, n-1)


# driver function
if __name__ == '__main__':
	arr = [1, 3, 4, 9, 10, 3]
	n = len(arr)

	# Answer queries
	i, j = 1, 4
	print(count_in_range(arr, n, i, j))

	i, j = 9, 12
	print(count_in_range(arr, n, i, j))
C#
using System;

public class SegmentTree {
	private int[] tree;
	private int low, high;

	public SegmentTree(int n) { tree = new int[4 * n]; }

	public void Build(int[] arr, int v, int tl, int tr)
	{
		if (tl == tr) {
			tree[v] = (arr[tl] >= low && arr[tl] <= high)
						? 1
						: 0;
		}
		else {
			int tm = (tl + tr) / 2;
			Build(arr, v * 2, tl, tm);
			Build(arr, v * 2 + 1, tm + 1, tr);
			tree[v] = tree[v * 2] + tree[v * 2 + 1];
		}
	}

	public int Query(int v, int tl, int tr, int l, int r)
	{
		if (l > r) {
			return 0;
		}
		if (l == tl && r == tr) {
			return tree[v];
		}
		int tm = (tl + tr) / 2;
		return Query(v * 2, tl, tm, l, Math.Min(r, tm))
			+ Query(v * 2 + 1, tm + 1, tr,
					Math.Max(l, tm + 1), r);
	}

	public void Update(int v, int tl, int tr, int i,
					int val)
	{
		if (tl == tr) {
			tree[v] = (val >= low && val <= high) ? 1 : 0;
		}
		else {
			int tm = (tl + tr) / 2;
			if (i <= tm) {
				Update(v * 2, tl, tm, i, val);
			}
			else {
				Update(v * 2 + 1, tm + 1, tr, i, val);
			}
			tree[v] = tree[v * 2] + tree[v * 2 + 1];
		}
	}

	public void SetRange(int l, int h)
	{
		low = l;
		high = h;
	}
}

public class Program {
	public static int CountInRange(int[] arr, int n, int x,
								int y)
	{
		SegmentTree st = new SegmentTree(n);
		st.SetRange(x, y);
		st.Build(arr, 1, 0, n - 1);
		return st.Query(1, 0, n - 1, 0, n - 1);
	}

	public static void Main()
	{
		int[] arr = { 1, 3, 4, 9, 10, 3 };
		int n = arr.Length;

		// Answer queries
		int i = 1, j = 4;
		Console.WriteLine(CountInRange(arr, n, i, j));

		i = 9;
		j = 12;
		Console.WriteLine(CountInRange(arr, n, i, j));
	}
}
JavaScript
class SegmentTree {
	constructor(n) {
		this.tree = new Array(4 * n).fill(0);
		this.low = 0;
		this.high = 0;
	}

	// build the tree with array elements
	build(arr, v, tl, tr) {
		if (tl === tr) {
			this.tree[v] = (arr[tl] >= this.low && arr[tl] <= this.high) ? 1 : 0;
		} else {
			const tm = Math.floor((tl + tr) / 2);
			this.build(arr, v * 2, tl, tm);
			this.build(arr, v * 2 + 1, tm + 1, tr);
			this.tree[v] = this.tree[v * 2] + this.tree[v * 2 + 1];
		}
	}

	// query the tree for given range
	query(v, tl, tr, l, r) {
		if (l > r) {
			return 0;
		}
		if (l === tl && r === tr) {
			return this.tree[v];
		}
		const tm = Math.floor((tl + tr) / 2);
		return this.query(v * 2, tl, tm, l, Math.min(r, tm))
			+ this.query(v * 2 + 1, tm + 1, tr, Math.max(l, tm + 1), r);
	}

	// update tree at index i with given value
	update(v, tl, tr, i, val) {
		if (tl === tr) {
			this.tree[v] = (val >= this.low && val <= this.high) ? 1 : 0;
		} else {
			const tm = Math.floor((tl + tr) / 2);
			if (i <= tm) {
				this.update(v * 2, tl, tm, i, val);
			} else {
				this.update(v * 2 + 1, tm + 1, tr, i, val);
			}
			this.tree[v] = this.tree[v * 2] + this.tree[v * 2 + 1];
		}
	}

	// set range for the tree
	setRange(l, h) {
		this.low = l;
		this.high = h;
	}
}

// function to count elements within given range
function countInRange(arr, n, x, y) {
	const st = new SegmentTree(n);
	st.setRange(x, y);
	st.build(arr, 1, 0, n - 1);
	return st.query(1, 0, n - 1, 0, n - 1);
}

// driver function
function main() {
	const arr = [1, 3, 4, 9, 10, 3];
	const n = arr.length;

	// Answer queries
	let i = 1, j = 4;
	console.log(countInRange(arr, n, i, j));

	i = 9;
	j = 12;
	console.log(countInRange(arr, n, i, j));
}

main();

Output
4 2 

Time Complexity: O((n + m) * log n) 
Auxiliary Space: O(n)

[Efficient Approach] Using Sorting and Binary Search

The idea is to sort the array and then use binary search to find the lower and upper bounds of the range [x, y] for each query. The count of elements in the range is then calculated as right - left + 1.

Step by step approach:

  1. Sort the array to enable efficient binary search for range queries.
  2. For each query [x, y], check if the range is outside array bounds; if so, set count to 0.
  3. Use binary search to find the lower bound (first element >= x) and upper bound (last element <= y).
  4. Calculate the count as max(0, right - left + 1) and store the result.
C++
// C++ program to count number of elements
// with values in given range.
#include <bits/stdc++.h>
using namespace std;

// function to count elements within given range
vector<int> countInRange(vector<int> &arr, 
vector<vector<int>> &queries) {
    
    int n = arr.size(), m = queries.size();
    
    // Sort the array 
    sort(arr.begin(), arr.end());
    
    vector<int> ans(m);
    
    // For each query 
    for (int i=0; i<m; i++) {
        
        int x = queries[i][0], y = queries[i][1];
        
        // If array elements do not fall in 
        // range 
        if (y < arr[0] || x > arr[n-1]) {
            ans[i] = 0;
            continue;
        }
        
        int left=n-1, right=0;
        
        int s = 0, e = n-1;
        
        // Find the lower bound
        while (s<=e) {
            int mid = s + (e-s)/2;
            if (arr[mid] < x) {
                s = mid + 1;
            } else {
                left = mid;
                e = mid - 1;
            }
        }
        
        s = 0; e = n-1;
        
        // Find upper bound
        while (s<=e) {
            int mid = s + (e-s)/2;
            if (arr[mid] > y) {
                e = mid - 1;
            } else {
                right = mid;
                s = mid + 1;
            }
        }
        
        ans[i] = max(0, right - left + 1);
    }
    
    return ans;
}

int main() {
    vector<int> arr = { 1, 3, 4, 9, 10, 3 };
    vector<vector<int>> queries = {{1, 4}, {9, 12}};

    vector<int> ans = countInRange(arr, queries);
    
    for (auto val: ans) {
        cout << val << " ";
    }
    cout << endl;
    
    return 0;
}
Java
// Java program to count number of elements
// with values in given range.

import java.util.Arrays;

class GfG {
    
    // function to count elements within given range
    static int[] countInRange(int[] arr, int[][] queries) {
        int n = arr.length, m = queries.length;

        // Sort the array 
        Arrays.sort(arr);

        int[] ans = new int[m];

        // For each query 
        for (int i = 0; i < m; i++) {
            int x = queries[i][0], y = queries[i][1];

            // If array elements do not fall in range 
            if (y < arr[0] || x > arr[n - 1]) {
                ans[i] = 0;
                continue;
            }

            int left = n - 1, right = 0;
            int s = 0, e = n - 1;

            // Find the lower bound
            while (s <= e) {
                int mid = s + (e - s) / 2;
                if (arr[mid] < x) {
                    s = mid + 1;
                } else {
                    left = mid;
                    e = mid - 1;
                }
            }

            s = 0; e = n - 1;

            // Find upper bound
            while (s <= e) {
                int mid = s + (e - s) / 2;
                if (arr[mid] > y) {
                    e = mid - 1;
                } else {
                    right = mid;
                    s = mid + 1;
                }
            }

            ans[i] = Math.max(0, right - left + 1);
        }

        return ans;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 4, 9, 10, 3};
        int[][] queries = {{1, 4}, {9, 12}};

        int[] ans = countInRange(arr, queries);

        for (int val : ans) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}
Python
# Python program to count number of elements
# with values in given range.

import bisect

# function to count elements within given range
def countInRange(arr, queries):
    n = len(arr)
    m = len(queries)
    
    # Sort the array 
    arr.sort()
    
    ans = [0] * m

    # For each query 
    for i in range(m):
        x, y = queries[i]

        # If array elements do not fall in range 
        if y < arr[0] or x > arr[n - 1]:
            ans[i] = 0
            continue

        # Find the lower bound
        left = bisect.bisect_left(arr, x)

        # Find the upper bound
        right = bisect.bisect_right(arr, y) - 1

        ans[i] = max(0, right - left + 1)

    return ans

if __name__ == "__main__":
    arr = [1, 3, 4, 9, 10, 3]
    queries = [[1, 4], [9, 12]]

    ans = countInRange(arr, queries)

    print(" ".join(map(str, ans)))
C#
// C# program to count number of elements
// with values in given range.

using System;

class GfG {
    
    // function to count elements within given range
    static int[] countInRange(int[] arr, int[][] queries) {
        int n = arr.Length, m = queries.Length;

        // Sort the array 
        Array.Sort(arr);

        int[] ans = new int[m];

        // For each query 
        for (int i = 0; i < m; i++) {
            int x = queries[i][0], y = queries[i][1];

            // If array elements do not fall in range 
            if (y < arr[0] || x > arr[n - 1]) {
                ans[i] = 0;
                continue;
            }

            int left = n - 1, right = 0;
            int s = 0, e = n - 1;

            // Find the lower bound
            while (s <= e) {
                int mid = s + (e - s) / 2;
                if (arr[mid] < x) {
                    s = mid + 1;
                } else {
                    left = mid;
                    e = mid - 1;
                }
            }

            s = 0; e = n - 1;

            // Find upper bound
            while (s <= e) {
                int mid = s + (e - s) / 2;
                if (arr[mid] > y) {
                    e = mid - 1;
                } else {
                    right = mid;
                    s = mid + 1;
                }
            }

            ans[i] = Math.Max(0, right - left + 1);
        }

        return ans;
    }

    static void Main(string[] args) {
        int[] arr = {1, 3, 4, 9, 10, 3};
        int[][] queries = { new int[] {1, 4}, new int[] {9, 12} };

        int[] ans = countInRange(arr, queries);

        Console.WriteLine(string.Join(" ", ans));
    }
}
JavaScript
// JavaScript program to count number of elements
// with values in given range.

// function to count elements within given range
function countInRange(arr, queries) {
    let n = arr.length, m = queries.length;

    // Sort the array 
    arr.sort((a, b) => a - b);

    let ans = new Array(m).fill(0);

    // For each query 
    for (let i = 0; i < m; i++) {
        let x = queries[i][0], y = queries[i][1];

        // If array elements do not fall in range 
        if (y < arr[0] || x > arr[n - 1]) {
            ans[i] = 0;
            continue;
        }

        let left = n - 1, right = 0;
        let s = 0, e = n - 1;

        // Find the lower bound
        while (s <= e) {
            let mid = Math.floor(s + (e - s) / 2);
            if (arr[mid] < x) {
                s = mid + 1;
            } else {
                left = mid;
                e = mid - 1;
            }
        }

        s = 0; e = n - 1;

        // Find upper bound
        while (s <= e) {
            let mid = Math.floor(s + (e - s) / 2);
            if (arr[mid] > y) {
                e = mid - 1;
            } else {
                right = mid;
                s = mid + 1;
            }
        }

        ans[i] = Math.max(0, right - left + 1);
    }

    return ans;
}

let arr = [1, 3, 4, 9, 10, 3];
let queries = [[1, 4], [9, 12]];

let ans = countInRange(arr, queries);

console.log(ans.join(" "));

Output
4 2 

Time Complexity: O((m + n) * log n). O(n* log n) time is used to sort the array and for m queries, (log n) time is used to find the lower and upper bound.
Auxiliary Space: O(1)



Similar Reads