VOOZH about

URL: https://www.geeksforgeeks.org/dsa/range-based-count-of-x-in-sorted-array/

⇱ Range-Based Count of X in Sorted Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Range-Based Count of X in Sorted Array

Last Updated : 1 Aug, 2025

Given a sorted array arr[] and a list of queries represented as a 2D array queries[][]. Each query is a triplet of the form [l, r, x], where l and r are indices in the array, and x is the value to search for.
For each query, find how many times the number x appears in the subarray arr[l...r] (inclusive).

Examples:

Input: arr[] = [1, 2, 2, 4, 5, 5, 5, 8], queries[][] = [[0, 7, 5], [1, 2, 2], [0, 3, 7]]
Output: [3, 2, 0]
Explanation:
Query [0, 7, 5] → elements from index 0 to 7 are [1, 2, 2, 4, 5, 5, 5, 8]. Number 5 occurs 3 times.
Query [1, 2, 2] → subarray is [2, 2], and 2 occurs 2 times.
Query [0, 3, 7] → subarray is [1, 2, 2, 4], and 7 is not present → 0.

Input: arr[] = [1, 3, 3, 3, 6, 7, 8], queries[][] = [[0, 3, 3], [4, 6, 3], [1, 5, 6]]
Output: [3, 0, 1]
Explanation:
Query [0, 3, 3] → subarray [1, 3, 3, 3], and 3 appears 3 times.
Query [4, 6, 3] → subarray [6, 7, 8], 3 not found → 0.
Query [1, 5, 6] → subarray [3, 3, 3, 6, 7], and 6 occurs 1 time.

[Naive Approach] Naive Linear Scan - O(q × n) Time and O(1) Space

For each query, iterate through the subarray from index l to r, and count how many times x appears.


Output
3 2 0 

[Expected Approach] Using Binary Search

The idea is to use binary search (lower_bound and upper_bound) to find the first and last positions where the element x appears in the sorted array. Once we know all the positions where x occurs, we simply check how many of those lie within the given index range [l, r]. If there's no overlap between the index range of occurrences and the query's [l, r], we return 0. Otherwise, we return the number of overlapping positions, which is right - left + 1.

Step by Step Implementation:

  • For each query [l, r, x], extract l, r, and x.
  • Use lower_bound to find the first index where x could appear.
  • If x doesn't exist in the array, directly store 0 as the answer for this query.
  • Use upper_bound to find the first index where the value becomes greater than x; subtract 1 to get the last index of x.
  • Clamp the range of x's occurrences to within [l, r] using max(left, l) and min(right, r).
  • If the clamped range is valid (left ≤ right), count the occurrences as right - left + 1.
  • Otherwise, store 0 for this query.

Output
3 2 0 

Time Complexity: O(q × log n), for each of the q queries, we perform two binary searches (lower_bound and upper_bound) on the sorted array of size n.
Auxiliary Space : O(1)

Comment
Article Tags:
Article Tags: