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: [3,1,4,3] has pairs (3,3)=1, not enough. [3,1,4,3,2,2] has pairs (3,3)+(2,2)=2≥2✓. [3,1,4,3,2,2,4] has pairs (3,3)+(2,2)+(4,4)=3≥2✓. Total of 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 Good Subarrays: Find subarrays with ≥k pairs3143224Input: nums = [3,1,4,3,2,2,4], k = 2Finding Good Subarrays✓ [3,1,4,3,2,2]: pairs (3,3)+(2,2) = 2 ≥ 2✓ [3,1,4,3,2,2,4]: pairs (3,3)+(2,2)+(4,4) = 3 ≥ 2✓ [1,4,3,2,2,4]: pairs (2,2)+(4,4) = 2 ≥ 2✓ [4,3,2,2,4]: pairs (2,2)+(4,4) = 2 ≥ 2Result: 4 good subarrays found
Understanding the Visualization
1
Input
Array [3,1,4,3,2,2,4] with k=2
2
Process
Find subarrays with ≥2 pairs of equal elements
3
Output
Count of good subarrays = 4
Key Takeaway
🎯 Key Insight: Use sliding window with frequency counting to efficiently track pairs of equal elements in subarrays
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