Problem Description
Given an array of integers, nums, and an integer k, return the number of contiguous subarrays (good subarrays) that contain exactly k different integers. A good subarray is defined as one having exactly k unique integers.
Key Insights
- Count subarrays with exactly k distinct integers by leveraging the sliding window technique.
- Use the trick: the number of subarrays with exactly k distinct = subarrays with at most k distinct - subarrays with at most (k-1) distinct.
- Maintain a hash map (or dictionary) to count frequency of array elements as you expand and contract the sliding window.
- Carefully update your window boundaries to ensure the count is maintained correctly.
Space and Time Complexity
Time Complexity: O(n) for each helper sliding window (total O(n) since each element is processed a constant number of times) Space Complexity: O(n) in the worst case, due to the hash map storing frequencies of unique numbers.
Solution
To solve the problem, we use a sliding window technique combined with a helper function that counts subarrays with at most k distinct integers. The idea is:
- Create a helper function countAtMost(K) that returns the number of subarrays with at most K distinct integers.
- In the helper, maintain two pointers (left and right) for the sliding window and a frequency map.
- For each position of right pointer, update the frequency map. If the number of distinct integers exceeds K, move the left pointer to reduce it.
- The total subarrays ending at the current right are added to the answer.
- The final answer is: countAtMost(k) - countAtMost(k - 1).
This approach ensures we efficiently count valid subarrays without needing to re-calculate subarray properties repeatedly.