Count Substrings That Satisfy K-Constraint I - Sliding Window [JS]
Solution: Sliding Window
Anchor at the right pointer j and increment from 0 to n - 1.
Move up the left pointer i while both the number of zeros and ones exceeds k.
Count the number of substrings ending at each index j.
Time Complexity: O(n)
Space Complexity: O(1)
function countKConstraintSubstrings(s, k) {
let n = s.length, substrings = 0;
let zeros = 0, ones = 0;
for (let j = 0, i = 0; j < n; j++) {
zeros += s[j] === '0' ? 1 : 0;
ones += s[j] === '1' ? 1 : 0;
while (zeros > k && ones > k) {
zeros -= s[i] === '0' ? 1 : 0;
ones -= s[i] === '1' ? 1 : 0;
i++;
}
substrings += j - i + 1;
}
return substrings;
};
Comments
Post a Comment