Count the Number of Good Subarrays - Problem
You're given an integer array nums and an integer k. Your task is to count how many good subarrays exist in the array.
A subarray is considered good if it contains at least k pairs of indices (i, j) where i < j and nums[i] == nums[j]. In other words, you need at least k pairs of duplicate elements within the subarray.
Key Points:
- A subarray is a contiguous sequence of elements
- We're counting pairs of equal elements at different positions
- The pairs must satisfy
i < j(left element comes before right element) - We need at least
ksuch pairs for a subarray to be good
Example: In array [1,1,1] with k=1, the subarray [1,1,1] has 3 pairs: (0,1), (0,2), (1,2) - so it's definitely good!
Input & Output
example_1.py โ Basic case
$
Input:
nums = [1,1,1], k = 1
โบ
Output:
3
๐ก Note:
The subarrays [1,1], [1,1], and [1,1,1] each have at least 1 pair of equal elements. Subarray [1,1,1] has 3 pairs: (0,1), (0,2), (1,2).
example_2.py โ Mixed elements
$
Input:
nums = [3,1,4,3,2,2,4], k = 2
โบ
Output:
4
๐ก Note:
Good subarrays need at least 2 pairs. Examples include [3,1,4,3,2,2] with pairs of 3's and 2's, and longer subarrays containing these pairs.
example_3.py โ No good subarrays
$
Input:
nums = [1,2,3,4,5], k = 1
โบ
Output:
0
๐ก Note:
All elements are unique, so no pairs exist. No subarray can have at least 1 pair of equal elements.
Visualization
Tap to expand
Understanding the Visualization
1
Expand the Party
Add a new person to the right side of our group
2
Count New Handshakes
New handshakes = number of people already in group with same name
3
Check if Party is Good
If total handshakes >= k, this group and all larger groups are good
4
Shrink if Needed
Remove people from left to optimize our counting
Key Takeaway
๐ฏ Key Insight: The sliding window approach transforms a complex O(nยณ) problem into an elegant O(n) solution by intelligently tracking pair formation!
Time & Space Complexity
Time Complexity
O(n)
Each element is visited at most twice (once by right pointer, once by left)
โ Linear Growth
Space Complexity
O(n)
Hash map stores frequency of unique elements in current window
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- 1 โค k โค nums.length * (nums.length - 1) / 2
- Time limit: 2 seconds
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code