Count Substrings That Satisfy K-Constraint I - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "10101", k = 1
›
Output:
12
💡 Note:
All substrings with length 1 satisfy the constraint (5 substrings). Substrings "10", "01", "10", "01" also satisfy it (4 more). Some length-3 substrings like "010" satisfy it too, totaling 12.
Example 2 — All Same Character
$
Input:
s = "1111", k = 2
›
Output:
10
💡 Note:
All substrings satisfy the constraint since we have only 1s and the constraint allows up to 2 of any character. Total substrings = n(n+1)/2 = 4×5/2 = 10.
Example 3 — Small k
$
Input:
s = "11001", k = 1
›
Output:
9
💡 Note:
Single characters always satisfy (5). "10", "00", "01" satisfy the constraint (3 more). "1100" has 2 ones and 2 zeros, violating the constraint for k=1. One more valid substring gives us 9.
Constraints
- 1 ≤ s.length ≤ 1000
- s consists only of '0' and '1'
- 1 ≤ k ≤ s.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary string s and constraint k
2
Process
Check each substring's 0s and 1s count
3
Output
Count of substrings where either count ≤ k
Key Takeaway
🎯 Key Insight: A substring is valid if it contains at most k zeros OR at most k ones
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code