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 with K-Constraint INPUT Binary String s: 1 0 1 0 1 0 1 2 3 4 Constraint k = 1 Max 0s OR Max 1s Valid if: count(0) <= 1 OR count(1) <= 1 Example valid: "1", "10", "01" Invalid: "1010" (2 zeros, 2 ones) ALGORITHM STEPS 1 Sliding Window Use two pointers L, R 2 Expand Right Count 0s and 1s in window 3 Shrink Left If both counts > k, move L until valid 4 Count Substrings Add (R - L + 1) to result Window Example: 1 0 1 0 1 L R Substrings: 3 FINAL RESULT 12 substrings Substring Breakdown: Length 1: 5 (all single chars) Length 2: 4 ("10","01","10","01") Length 3: 2 ("010","101") Length 4: 1 ("0101") Length 5: 0 (invalid) 5 + 4 + 2 + 1 + 0 = 12 OK - Verified Key Insight: The sliding window approach works because valid substrings form a contiguous range. For each right pointer R, all substrings ending at R and starting from L to R are valid. This gives us (R - L + 1) valid substrings per position, achieving O(n) time complexity. TutorialsPoint - Count Substrings That Satisfy K-Constraint I | Sliding Window Approach
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