![]() |
VOOZH | about |
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.
Table of Content
For each query, iterate through the subarray from index l to r, and count how many times x appears.
3 2 0
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:
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)