![]() |
VOOZH | about |
Given an array arr[] of integers and a 2D array queries[][], where each queries[i] contains three integers: l, r, and x. For each query, determine how many times the element x appears in the subarray of arr[] from index l to r (both inclusive).
For each query, return the count of occurrences of x in the specified range.
Examples:
Input: arr []= [1, 2, 1, 3, 1, 2, 3], queries[][] = [[0, 4, 1], [2, 5, 2], [1, 6, 3], [0, 6, 5]]
Output: [3, 1, 2, 0]
Explanation:
query [0, 4, 1] → Subarray = [1, 2, 1, 3, 1], 1 appears 3 times
query [2, 5, 2] → Subarray = [1, 3, 1, 2], 2 appears 1 time
query [1, 6, 3] → Subarray = [2, 1, 3, 1, 2, 3] 3 appears 2 times
query [0, 6, 5] → Subarray = [1, 2, 1, 3, 1, 2, 3], 5 appears 0 timesInput: arr[] = [11, 21, 51, 101, 11, 51], queries[][] = [[0, 4, 11], [2, 5, 51]]
Output: [2, 2]
Explanation:
query [0, 4, 11] → Subarray = [11, 21, 51, 101, 11], 11 appears 2 times
query [2, 5, 51] → Subarray = [51, 101, 11, 51], 51 appears 2 times
Table of Content
The idea is to iterate over each query and scan the subarray from index l to r, counting how many times the element x appears. This is done using a simple linear loop for every query without any preprocessing.
3 1 2 0
The idea is to precompute the positions of each element in the array and store them in a map. For each query, we find how many times x appears between indices l and r by applying lower_bound and upper_bound on the stored index list of x.
Step by Step Implementation:
Dry Run Example:
arr = [1, 2, 1, 3, 1, 2, 3]1 → [0, 2, 4], 2 → [1, 5], 3 → [3, 6]x=1 indices are [0, 2, 4]. lower_bound(0) is at index 0, upper_bound(4) is at index 3 (out of bounds) → Count = 3 - 0 = 3x=2 indices are [1, 5]. lower_bound(2) is at index 1, upper_bound(5) is at index 2 (out of bounds) → Count = 2 - 1 = 1x=3 indices are [3, 6]. lower_bound(1) is at index 0, upper_bound(6) is at index 2 (out of bounds) → Count = 2 - 0 = 2x=5 is not found in the index map → Count = 0Final Result: [3, 1, 2, 0]
3 1 2 0
Time Complexity: O(n × logn + q × log k), preprocessing the map takes O(n × log n) time, where n is the size of the array then for each of the q queries, we perform two binary searches on the index list of size k (number of times x appears), costing O(log k) per query.
Auxiliary Space: O(n), we use a map to store indices of each distinct element. In the worst case (all elements unique), the total space used across all vectors is proportional to the array size n.