Range Frequency Queries - Problem
Design a data structure to find the frequency of a given value in a given subarray.
The frequency of a value in a subarray is the number of occurrences of that value in the subarray.
Implement the RangeFreqQuery class:
RangeFreqQuery(int[] arr)Constructs an instance of the class with the given 0-indexed integer arrayarr.int query(int left, int right, int value)Returns the frequency ofvaluein the subarrayarr[left...right].
A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of arr between indices left and right (inclusive).
Input & Output
Example 1 — Basic Range Query
$
Input:
arr = [1,2,2,3,1], operations = [[0,4,1],[1,3,2]]
›
Output:
[2,2]
💡 Note:
For query [0,4,1]: value 1 appears at indices 0 and 4, both in range → count = 2. For query [1,3,2]: value 2 appears at indices 1 and 2, both in range → count = 2.
Example 2 — Value Not in Range
$
Input:
arr = [1,1,1,1], operations = [[1,2,2]]
›
Output:
[0]
💡 Note:
Query [1,2,2]: looking for value 2 in range [1,2], but value 2 doesn't exist in the array → count = 0.
Example 3 — Single Element Range
$
Input:
arr = [5,3,5,1,5], operations = [[0,0,5],[2,2,5]]
›
Output:
[1,1]
💡 Note:
Query [0,0,5]: range contains only index 0 with value 5 → count = 1. Query [2,2,5]: range contains only index 2 with value 5 → count = 1.
Constraints
- 1 ≤ arr.length ≤ 105
- 1 ≤ value ≤ 104
- 0 ≤ left ≤ right < arr.length
- At most 105 calls to query
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,2,2,3,1] and query range [1,3] for value 2
2
Process
Count occurrences of value 2 in positions 1, 2, 3
3
Output
Return frequency count: 2
Key Takeaway
🎯 Key Insight: Pre-organize indices by value to enable fast range counting with binary search
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code