1004. Distinct in Range
A radio station logged the frequency nums[i] it heard at each of n consecutive moments. Each entry [a, b] of queries asks about the window of moments from a % n to b % n inclusive (swap the two ends if the first is larger).
For every query return the number of different frequencies heard inside its window, in query order.
Re-scanning every window is too slow when the log and the number of questions are both large. Aim for O((n + q) log n) time and O(n + q) space.
Example 1
- Input:
- nums = [8,3,8,5,3,9,5,8]queries = [[0,3],[2,6],[7,1],[4,4]]
- Output:
- [3,4,4,1]
- Explanation:
Positions 0..3 hold 8,3,8,5, giving 3 distinct values; positions 2..6 hold 8,5,3,9,5, giving 4; the pair (7,1) is read as positions 1..7, which contain 3,5,8,9, so 4; a single position gives 1.
Example 2
- Input:
- nums = [40,40,41,40,42]queries = [[0,4],[1,2],[3,4],[9,10]]
- Output:
- [3,2,2,3]
- Explanation:
Positions 0..4 hold 40,40,41,40,42 (3 distinct); 1..2 hold 40,41 (2); 3..4 hold 40,42 (2); the pair (9,10) is read modulo 5 as positions 4..0, i.e. 0..4, so 3.
Constraints
1 ≤ n = nums.length ≤ 105
0 ≤ q = queries.length ≤ 2000
0 ≤ nums[i] ≤ 109; 0 ≤ a, b ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms
Expected complexity
- Time
- O((n + q) log n)
- Space
- O(n + q)