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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code