Count the Number of Good Subarrays Problem
Description
LeetCode Problem 2537.
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.
Example 1:
Input: nums = [1,1,1,1,1], k = 10
Output: 1
Explanation: The only good subarray is the array nums itself.
Example 2:
Input: nums = [3,1,4,3,2,2,4], k = 2
Output: 4
Explanation: There are 4 different good subarrays:
- [3,1,4,3,2,2] that has 2 pairs.
- [3,1,4,3,2,2,4] that has 3 pairs.
- [1,4,3,2,2,4] that has 2 pairs.
- [4,3,2,2,4] that has 2 pairs.
Constraints:
1 <= nums.length <= 10^51 <= nums[i], k <= 10^9
Solution
Approach: Sliding Window with a Hash Map
A subarray's pair count only grows when it gets longer, so once a window [i, r] has at least k equal pairs, every window that starts further left and ends at r does too. That lets us count by the right end.
Keep a map cnt of how often each value occurs in the window, the number cur of equal pairs in it, and the left end i. For each new right element x, cur grows by cnt[x] (it pairs with each earlier copy), then cnt[x] grows by 1.
Now move i right while the window would still have at least k pairs without its leftmost element. Removing a value v loses cnt[v] - 1 pairs. After that, if cur >= k, the starts 0..i all work, so add i + 1 to the answer.
Complexity: O(n) time, since each element enters and leaves the window once, and O(n) extra space for the map.
class Solution:
def countGood(self, nums: List[int], k: int) -> int:
cnt = Counter()
ans = cur = 0
i = 0
for x in nums:
cur += cnt[x]
cnt[x] += 1
while cur - cnt[nums[i]] + 1 >= k:
cnt[nums[i]] -= 1
cur -= cnt[nums[i]]
i += 1
if cur >= k:
ans += i + 1
return ans