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 most k.
  • The number of '1's in the string is at most k.

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
Count Substrings That Satisfy K-ConstraintInput: s = "10101", k = 110101Length 1: 5Length 2: 4Length 3: 2Length 4+: 1K-Constraint: zeros ≤ k OR ones ≤ kValid substrings: "1", "0", "1", "0", "1", "10", "01", "10", "01", "010", "101", "0101"Output: 12 valid substrings
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
Asked in
Microsoft 15 Amazon 12
12.5K Views
Medium Frequency
~15 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen