VOOZH about

URL: https://www.geeksforgeeks.org/dsa/queries-counts-array-elements-values-given-range/

⇱ Queries for counts of array values in a given range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queries for counts of array values in a given range

Last Updated : 20 Mar, 2025

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.


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.


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.

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)

Comment