923. Range Frequency Desk
A weather station stores a long, fixed list of integer sensor codes. Build the class RangeFrequency; its constructor receives the array arr, and the array never changes afterwards.
query(left, right, value) returns how many positions i with left <= i <= right (0-indexed, both ends included) satisfy arr[i] == value. The value may not occur at all, in which case the answer is 0.
Many queries will be asked, so scanning the range each time is too slow in the intended solution. Preprocess in O(n log n); each query should then take O(log n).
Example 1
- Input:
- operations = ["RangeFrequency","query","query","query","query","query"]arguments = [[[9,4,9,9,2,4,9,7]],[0,7,9],[1,3,9],[4,5,4],[3,3,2],[0,7,5]]
- Output:
- [null,4,2,1,0,0]
- Explanation:
The value 9 occurs four times overall but only twice inside positions 1 to 3; value 4 occurs once in positions 4 to 5; position 3 holds 9, not 2; and 5 never appears.
Example 2
- Input:
- operations = ["RangeFrequency","query","query","query","query"]arguments = [[[6,6,6,6]],[0,0,6],[0,3,6],[2,3,6],[1,2,0]]
- Output:
- [null,1,4,2,0]
- Explanation:
Every cell holds 6, so the answer equals the length of the queried range, except for the absent value 0.
Constraints
1 ≤ arr.length ≤ 100000
0 ≤ arr[i], value ≤ 10000
0 ≤ left ≤ right < arr.length
At most 100000 calls to query
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(n log n) build, O(log n) per query
- Space
- O(n)