1311. Window Mode Report
A streaming service logs the id of the song played in every slot of a long playlist history, stored in nums. For each window of k consecutive slots, the editors want the song that was played the most often inside that window.
Return an array of length nums.length - k + 1 whose entry s is the most frequent value among nums[s..s+k-1], for every start s from 0 upwards, in that order. When two or more values share the highest frequency inside a window, report the numerically smallest of them.
Rebuilding the counts for every window is too slow for long histories. Update the counts as the window moves one slot at a time and keep a structure that can tell you the current leader quickly, discarding outdated entries as you go. The intended solution runs in O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [1,3,3,2,2,2], k = 3
- Output:
- [3,3,2,2]
- Explanation:
The windows are [1,3,3], [3,3,2], [3,2,2] and [2,2,2], whose most frequent values are 3, 3, 2 and 2.
Example 2
- Input:
- nums = [4,6,6,4], k = 2
- Output:
- [4,6,4]
- Explanation:
Each window of two has two values with frequency 1 or one value with frequency 2; ties go to the smaller value, giving 4, 6, 4.
Example 3
- Input:
- nums = [8,8,8], k = 3
- Output:
- [8]
- Explanation:
There is a single window and 8 fills it.
Constraints
-
1 ≤ k ≤ nums.length ≤ 105 -
1 ≤ nums[i] ≤ 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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)