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 k such 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
Sliding Window: The Party AnalogyAABAWINDOW1 pair2 pairs3 pairsFrequency Counter:A: 3 peopleB: 1 personTotal pairs: 3Status: Good party! โœ“Key Insight:When person A joins, new pairs = existing A countAdding 3rd person A creates 2 new pairs with existing AsTime Complexity: O(n) | Space Complexity: O(n)
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)

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map stores frequency of unique elements in current window

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค k โ‰ค nums.length * (nums.length - 1) / 2
  • Time limit: 2 seconds
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
31.2K Views
Medium-High Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen