Count the Number of Good Subarrays - 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 least k 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,1,4,3,2,2,4], k = 2
Output: 4
💡 Note: Good subarrays include: [3,1,4,3,2,2] has 2 pairs: (3,3) at indices (0,3) and (2,2) at indices (4,5), so 2≥2✓. [3,1,4,3,2,2,4] has 3 pairs: (3,3), (2,2), and (4,4), so 3≥2✓. Many other subarrays also qualify, totaling 4 good subarrays.
Example 2 — Small Array
$ Input: nums = [1,1,1,1,1], k = 10
Output: 1
💡 Note: Only the full array [1,1,1,1,1] has enough pairs: C(5,2)=10 pairs of equal elements, which equals k=10.
Example 3 — No Good Subarrays
$ Input: nums = [1,2,3,4], k = 1
Output: 0
💡 Note: All elements are distinct, so no pairs of equal elements exist. No subarray can have ≥1 pairs.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Count the Number of Good Subarrays INPUT nums array: 3 1 4 3 2 2 4 0 1 2 3 4 5 6 k = 2 (min pairs needed) Good Pair Definition: i < j AND arr[i] == arr[j] Possible pairs in full array: (0,3): 3==3 [OK] (2,6): 4==4 [OK] (4,5): 2==2 [OK] nums = [3,1,4,3,2,2,4] k = 2 ALGORITHM STEPS Sliding Window Approach 1 Initialize Window left=0, pairCount=0 countMap = {} 2 Expand Right Add nums[right] to window pairs += count[nums[right]] 3 Shrink if pairs >= k While pairs >= k: result += n - right shrink from left 4 Count Subarrays Each valid left adds (n - right) subarrays Window State Example: left right FINAL RESULT 4 good subarrays Good Subarrays Found: [3,1,4,3,2,2] idx 0-5 pairs: (0,3), (4,5) = 2 [3,1,4,3,2,2,4] idx 0-6 pairs: (0,3), (2,6), (4,5) = 3 [1,4,3,2,2,4] idx 1-6 pairs: (1,5), (3,4) = 2 [4,3,2,2,4] idx 2-6 pairs: (0,4), (2,3) = 2 Output: 4 All have >= 2 pairs Key Insight: When we add element x to window, new pairs formed = current count of x in window. Once window has >= k pairs, ALL extensions to the right are also valid subarrays. Time: O(n) - each element added/removed once. Space: O(n) for frequency map. TutorialsPoint - Count the Number of Good Subarrays | Optimized Sliding Window
Asked in
Google 15 Meta 12 Amazon 10
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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