Count Substrings That Satisfy K-Constraint II - Problem
You are given a binary string s and an integer k. You are also given a 2D integer array queries, where queries[i] = [li, ri].
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
For each query, you need to count how many substrings within the range s[li..ri] satisfy the k-constraint.
Goal: Return an integer array answer, where answer[i] is the number of substrings of s[li..ri] that satisfy the k-constraint.
Example: If s = "0001111" and k = 2, then substrings like "00", "11", "001" all satisfy the constraint because they have ≤2 zeros OR ≤2 ones.
Input & Output
example_1.py — Basic Example
$
Input:
s = "0001111", k = 2, queries = [[0,6]]
›
Output:
[26]
💡 Note:
All substrings of s satisfy the constraint since each has ≤2 zeros OR ≤2 ones. Total substrings = 7×8/2 = 28, but some violate the constraint. After checking: 26 valid substrings.
example_2.py — Multiple Queries
$
Input:
s = "010101", k = 1, queries = [[0,5],[1,4],[2,3]]
›
Output:
[15,9,3]
💡 Note:
Query [0,5]: Full string has many valid substrings. Query [1,4]: Substring "1010" analysis. Query [2,3]: Substring "01" has 3 valid substrings: "0", "1", "01".
example_3.py — Edge Case
$
Input:
s = "11111", k = 1, queries = [[0,4]]
›
Output:
[15]
💡 Note:
All substrings satisfy constraint (≤1 ones OR ≤1 zeros). Since all are 1s, each substring has ≤1 zeros, so all 15 possible substrings are valid.
Constraints
- 1 ≤ s.length ≤ 105
- s[i] is either '0' or '1'
- 1 ≤ k ≤ s.length
- 1 ≤ queries.length ≤ 105
- queries[i] = [li, ri]
- 0 ≤ li ≤ ri < s.length
Visualization
Tap to expand
Understanding the Visualization
1
Set Tolerance Level
Establish k as maximum acceptable defects of either type
2
Find Valid Segments
Use sliding window to efficiently find all valid chip segments
3
Precompute Boundaries
Record the furthest valid position for each starting point
4
Answer Inspections
When managers ask about specific sections, use precomputed data
Key Takeaway
🎯 Key Insight: By precomputing the furthest valid position for each starting point using sliding window, we can answer any range query in O(1) time using mathematical formulas, achieving optimal O(N + Q) complexity.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code