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