Skip to main content

2537.js

/** ------------------------------------------------------------------------------
*
* 2537. Count the Number of Good Subarrays
* Topics: Hash Table, Sliding Window
* https://leetcode.com/problems/count-the-number-of-good-subarrays/description/?envType=daily-question&envId=2025-04-16
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
function countGood(nums, k) {
let n = nums.length
let good = 0 // Stores the number of good subarrays
let freqMap = new Map() // To track the frequency of elements
let pairCount = 0 // To track how many pairs are present in the current window
let i = 0 // Left pointer of the sliding window

for (let j = 0; j < n; j++) {
// Update the frequency of the current element (nums[j])
let currentFreq = freqMap.get(nums[j]) || 0
// Add the new pairs formed with this element
pairCount += currentFreq

// Increase the frequency of nums[j] in the map
freqMap.set(nums[j], currentFreq + 1)

// Now check if we have enough pairs
while (pairCount >= k) {
// All subarrays starting from `i` to `j` are valid
good += n - j

// Now shrink the window from the left (increment `i`)
let leftFreq = freqMap.get(nums[i]) || 0
pairCount -= leftFreq - 1 // We remove the contribution of nums[i]
freqMap.set(nums[i], leftFreq - 1)
i++
}
}

return good
}

console.log(countGood([1, 1, 1, 1, 1], 10))