Count the Number of Good Subarrays - Sliding Window [JS]
Solution: Sliding Window
If a subarray has at least k good pairs, then we know that expanding the subarray will always also result in at least k good pairs.
Keep track of the count of occurances of each number.
We have two pointers i and j for our sliding window.
- As we move
jup, we will gain anothercount[nums[j]]good pairs. - Move
iup while the good pairs >=k. When we moveiup, we subtractcount[nums[i]] - 1good pairs. - Then, we will know that all subarrays with start index between
0andi - 1, and end index atjwill have at leastkgood pairs.
Time Complexity: O(n)
Space Complexity: O(n)
var countGood = function(nums, k) {
let n = nums.length, count = {}, goodPairs = 0, ans = 0;
for (let j = 0, i = 0; j < n; j++) {
goodPairs += count[nums[j]] || 0;
count[nums[j]] = (count[nums[j]] || 0) + 1;
while (goodPairs >= k) {
goodPairs -= --count[nums[i]];
i++;
}
ans += i;
}
return ans;
};
Comments
Post a Comment