Problem Description
Given an integer array nums and an integer k, a subarray is considered good if, within the subarray, there are at least k pairs of indices (i, j) with i < j such that nums[i] equals nums[j]. The task is to count the total number of good subarrays in nums.
Key Insights
- Utilize a sliding window approach to keep track of a contiguous subarray.
- Maintain a frequency map (hash table) to count the occurrences of each element in the window.
- As you extend the window by moving the right pointer, update the number of pairs by adding the current frequency of the new element.
- When the current window’s pair count reaches or exceeds k, every subarray that starts at the current left index and extends from the current right pointer to the end will also be good.
- Shrink the window from the left while the condition holds to count all valid subarrays starting from earlier positions.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array, since each element is processed at most twice. Space Complexity: O(n), due to the space used by the frequency map.
Solution
We use a two-pointer (sliding window) strategy with a hash table to maintain the frequency count of elements in the current subarray and a variable to keep track of the number of matching pairs. When extending the window (by moving the right pointer), we update the pair count by adding the current frequency (since each occurrence already in the window forms a new pair with the added element). Once the window has k or more pairs, we know that any subarray starting at the current left pointer and ending anywhere from the current right pointer to the end of the array automatically satisfies the condition. We then slide the left pointer inward, updating the frequency map and reducing the pair count accordingly. This method ensures that all good subarrays are counted in linear time.