Count Substrings That Satisfy K-Constraint I - Problem
You're given a binary string s (containing only '0's and '1's) and an integer k. Your task is to find how many substrings of s satisfy the k-constraint.
A substring satisfies the k-constraint if at least one of these conditions is true:
- The number of '0's in the substring is at most k
- The number of '1's in the substring is at most k
Example: If s = "10101" and k = 1, the substring "101" has 2 zeros and 1 one. Since the number of ones (1) β€ k (1), it satisfies the constraint!
Return the total count of all valid substrings.
Input & Output
example_1.py β Basic Case
$
Input:
s = "10101", k = 1
βΊ
Output:
12
π‘ Note:
The valid substrings are: "1" (1 one), "10" (1 zero, 1 one), "101" (1 zero), "0" (1 zero), "01" (1 zero, 1 one), "010" (2 zeros, 1 one - onesβ€k), "1" (1 one), "10" (1 zero, 1 one), "101" (1 zero), "0" (1 zero), "01" (1 zero, 1 one), "1" (1 one). Total: 12 substrings.
example_2.py β All Valid
$
Input:
s = "1001", k = 2
βΊ
Output:
10
π‘ Note:
With k=2, most substrings are valid since we allow up to 2 of each character. All 10 possible substrings satisfy the k-constraint: "1", "10", "100", "1001", "0", "00", "001", "0", "01", "1".
example_3.py β Edge Case
$
Input:
s = "111", k = 1
βΊ
Output:
6
π‘ Note:
All substrings contain only 1's, so they all satisfy 'ones β€ k' condition. The 6 substrings are: "1" (Γ3), "11" (Γ2), "111" (Γ1). Total: 3+2+1 = 6.
Constraints
- 1 β€ s.length β€ 105
- s[i] is either '0' or '1'
- 0 β€ k β€ s.length
- Each substring must be contiguous
Visualization
Tap to expand
Understanding the Visualization
1
Set Up Window
Start with an empty window at the beginning of the string
2
Expand Window
Keep adding items to the right side of the window
3
Check Validity
Window is valid if zeros β€ k OR ones β€ k (at least one condition)
4
Shrink If Needed
If both zeros > k AND ones > k, remove items from the left
5
Count Substrings
For current right position, count all valid substrings ending here
Key Takeaway
π― Key Insight: Instead of checking every substring individually (O(nΒ³)), we use a sliding window to find the furthest valid starting position for each ending position, then count all valid substrings in O(1) time per position, achieving optimal O(n) complexity.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code