Problem Description
Given an integer array nums and an integer k, find the number of distinct elements in every contiguous subarray of size k. For each sliding window, return the count of unique elements in that window.
Key Insights
- Use a sliding window to traverse the array with a fixed window size k.
- Leverage a hash table (dictionary or map) to count the frequency of elements within the current window.
- As the window slides, decrement the count of the element going out and increment (or add) the count of the new element coming in.
- When the count of an element drops to zero, remove it from the hash table to maintain an accurate count of distinct elements.
Space and Time Complexity
Time Complexity: O(n) – Each element is processed a constant number of times. Space Complexity: O(k) – The hash table stores up to k elements in the worst-case scenario.
Solution
We implement a sliding window approach with a hash table (or dictionary in Python; map in Java/C++) to track the frequencies of each element in the current window. Initially, populate the hash table with the first k elements and record the number of distinct keys. Then, for each step, slide the window by one position: decrement the frequency of the outgoing element and remove it from the hash table if its frequency becomes zero; increment or add the new incoming element’s frequency. Append the current number of distinct keys to the answer list. This efficiently computes the result for each window.