Problem 318
Count Distinct in Every Window
Medium · 20 pts · Array, Hash Table, Sliding Window
Problem
A window of size K slides over the array from left to right, one position at a time, so there are N - K + 1 windows. For each window, count how many different values it contains. Recounting every window from scratch takes O(N·K) time; keeping a running count of values as the window moves takes O(N).
Input
The first line contains N and K. The second line contains N integers.
Output
Print N - K + 1 counts, separated by spaces.
Constraints
1 <= K <= N <= 100000; 1 <= A[i] <= 100000
Example input
7 4 1 2 1 3 4 2 3
Example output
3 4 4 3
Explanation
With K = 4 in 1 2 1 3 4 2 3, the windows are [1 2 1 3], [2 1 3 4], [1 3 4 2] and [3 4 2 3], which contain 3, 4, 4 and 3 different values.