Problem
Given an integer array nums and an integer k, return the number of good subarrays of nums.
A subarray arr is good if there are at leastk pairs of indices (i, j) such that i < j and arr[i] == arr[j].
A subarray is a contiguous non-empty sequence of elements within an array.
Examples
Example 1
| |
Example 2
| |
Constraints
1 <= nums.length <= 10^51 <= nums[i], k <= 10^9
Solution
Method 1 - Sliding window technique
To solve the problem efficiently, we can use the sliding window approach combined with a hash map to track the frequency of elements in the current subarray window. The idea involves expanding the window to form valid subarrays (those with at least k good pairs) and contracting the window once the condition is violated.
Here is the approach:
- Use two pointers (
startandend) to maintain the sliding window. - Maintain a frequency count of elements in the current window using a hash map.
- For each new element added to the window (
endpointer increment), calculate the number of new good pairs added based on its frequency and update the total count. - Keep shrinking the window (increment the
startpointer) when the count of good pairs in the window meets or exceedsk. During shrinking, adjust frequencies and good pairs accordingly. - Accumulate the number of good subarrays across all valid windows.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n). Thestartandendpointers both traverse thenumsarray once, making the time complexityO(n). - Operations on the hash map (
freq) such as updating and accessing elements areO(1)due to average-case behaviour. - 🧺 Space complexity:
O(u). - The hash map (freq) stores counts of unique elements in the array. In the worst case, all elements are unique, making itO(u), whereuis the number of unique elements.