Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 16, 2025 16:24
Show Gist options
  • Save tatsuyax25/c7fbfd1433e80176d9b4d7b9a87a37d3 to your computer and use it in GitHub Desktop.
Save tatsuyax25/c7fbfd1433e80176d9b4d7b9a87a37d3 to your computer and use it in GitHub Desktop.
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
/**
* Function to count the number of "good" subarrays in an array.
* A "good" subarray is defined as having at least `k` pairs of indices `(i, j)`
* such that `nums[i] == nums[j]` and `i < j`.
*
* @param {number[]} nums - Array of integers to be evaluated.
* @param {number} k - Minimum number of pairs needed to consider a subarray "good".
* @return {number} - The total count of "good" subarrays.
*/
var countGood = function(nums, k) {
const count = new Map(); // Map to store the frequency of elements in the current window.
let left = 0; // Left pointer of the sliding window.
let pairCount = 0; // Current count of pairs in the sliding window.
let result = 0; // Result to store the total count of "good" subarrays.
// Iterate through the array using the right pointer.
for (let right = 0; right < nums.length; right++) {
const val = nums[right]; // Current value at the right pointer.
// Update the pair count based on the frequency of the current value.
pairCount += count.get(val) || 0;
// Increment the frequency of the current value in the map.
count.set(val, (count.get(val) || 0) + 1);
// While the number of pairs in the window meets or exceeds `k`,
// adjust the left pointer and update the result.
while (pairCount >= k) {
// Add the number of valid subarrays ending at `right` to the result.
result += nums.length - right;
const leftVal = nums[left]; // Value at the left pointer.
// Decrement the frequency of the left value in the map.
count.set(leftVal, count.get(leftVal) - 1);
// Update the pair count based on the reduced frequency.
pairCount -= count.get(leftVal);
left++; // Move the left pointer forward to shrink the window.
}
}
return result; // Return the total count of "good" subarrays.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment