Count Substrings That Satisfy K-Constraint I Problem
#3258
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3258.
You are given a binary string s and an integer k.
A binary string satisfies the k-constraint if either of the following conditions holds:
- The number of
0's in the string is at mostk. - The number of
1's in the string is at mostk.
Return an integer denoting the number of substrings of s that satisfy the k-constraint.
Example 1:
Input: s = "10101", k = 1
Output: 12
Explanation:
Every substring of s except the substrings "1010", "10101", and "0101" satisfies the k-constraint.
Example 2:
Input: s = "1010101", k = 2
Output: 25
Explanation:
Every substring of s except the substrings with a length greater than 5 satisfies the k-constraint.
Example 3:
Input: s = "11111", k = 1
Output: 15
Explanation:
All substrings of s satisfy the k-constraint.
Constraints:
1 <= s.length <= 501 <= k <= s.lengths[i]is either'0'or'1'.
Solution
Approach: Sliding Window
A substring satisfies the constraint when it has at most k zeros or at most k ones. Keep a window [l, r] and the counts of zeros and ones in it. After adding s[r], shrink from the left while both counts exceed k.
Once the window is valid, every substring that ends at r and starts inside the window is valid too (shrinking a valid substring keeps it valid), which gives r - l + 1 substrings. Add that for every r.
Complexity: O(n) time and O(1) extra space.
class Solution:
def countKConstraintSubstrings(self, s: str, k: int) -> int:
cnt = [0, 0]
ans = l = 0
for r, x in enumerate(map(int, s)):
cnt[x] += 1
while cnt[0] > k and cnt[1] > k:
cnt[int(s[l])] -= 1
l += 1
ans += r - l + 1
return ans