The Count Substrings That Satisfy K-Constraint I coding problem asks you to look at a binary string (consisting of '0's and '1's) and an integer . A substring is said to satisfy the "-constraint" if either the count of '0's in it is at most , OR the count of '1's in it is at most .
You need to find the total number of substrings that satisfy this condition.
This problem is a classic sliding window interview pattern question asked by Microsoft and Google. It tests the ability to translate a logical "OR" condition into a window-management strategy. It also checks if you can identify that once a window satisfies a condition, any further reduction of that window (making it smaller) will also satisfy the condition. This "monotonic" property is key to an efficient solution.
The Sliding Window pattern is the most efficient choice here.
left and right.right pointer and update the counts of '0's and '1's.left until the constraint is restored.right position, the number of valid substrings ending at right is right - left + 1.s = "10101", k = 1
right = 0: "1". 0 zeros, 1 one. Valid. Count += 1.right = 1: "10". 1 zero, 1 one. Valid. Count += 2 (substrings "0", "10").right = 2: "101". 1 zero, 2 ones. Valid (). Count += 3 ("1", "01", "101").right = 3: "1010". 2 zeros, 2 ones. Invalid (both ).left to 1: "010". Invalid.left to 2: "10". Valid (). Count += 2 ("0", "10").
... continue.left pointer moves.Whenever a problem asks to "Count all substrings satisfying a condition," check if the condition is "stable." If a substring is valid, does making it smaller (shrinking from either side) keep it valid? If yes, sliding window is your go-to tool.