Untitled

mail@pastecode.io avatar
unknown
javascript
a month ago
854 B
1
Indexable
Never
function countKPairSubarrays(numbers, k) {
    let count = 0;
    for (let start = 0; start < numbers.length; start++) {
        const freq = new Map();
        let pairsCount = 0;

        for (let end = start; end < numbers.length; end++) {
            const num = numbers[end];
            const prevCount = freq.get(num) || 0;
            freq.set(num, prevCount + 1);

            // When we have an even count of a number, we have a new pair
            if ((prevCount + 1) % 2 === 0) {
                pairsCount++;
            } else if (prevCount % 2 === 0) { // When we had a pair, but now we have an odd count
                pairsCount--;
            }

            // If we have at least k pairs, include this subarray in the count
            if (pairsCount >= k) {
                count++;
            }
        }
    }
    return count;
}
Leave a Comment