3258. Count Substrings That Satisfy K-Constraint I
Description
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'.
Solutions
Solution 1: Sliding Window
Thinking
The \(k\)-constraint asks that a substring has at most \(k\) zeros or at most \(k\) ones. \(n\le 50\) would allow listing substrings, but the constraint is monotone in the right end: once both counts exceed \(k\), the left end must move.
A sliding window keeps \(c_0,c_1\) and shrinks on overflow. Every substring ending at \(r\) with left end in \([l,r]\) is then valid, hence \(r-l+1\) of them. One linear pass.
We use two variables \(\textit{cnt0}\) and \(\textit{cnt1}\) to record the number of \(0\)s and \(1\)s in the current window, respectively. We use \(\textit{ans}\) to record the number of substrings that satisfy the \(k\) constraint, and \(l\) to record the left boundary of the window.
When we move the window to the right, if the number of \(0\)s and \(1\)s in the window both exceed \(k\), we need to move the window to the left until the number of \(0\)s and \(1\)s in the window are both no greater than \(k\). At this point, all substrings in the window satisfy the \(k\) constraint, and the number of such substrings is \(r - l + 1\), where \(r\) is the right boundary of the window. We add this count to \(\textit{ans}\).
Finally, we return \(\textit{ans}\).
The time complexity is \(O(n)\), where \(n\) is the length of the string \(s\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |