Count Substrings That Satisfy K-Constraint I - Sliding Window [JS]

Description 

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

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]