Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
0's in the string is at most k.1's in the string is at most k.Return an integer array answer, where answer[i] is the number of substrings of s[li..ri] that satisfy the k-constraint.
Example 1:
Input: s = "0001111", k = 2, queries = [[0,6]]
Output: [26]
Explanation:
For the query [0, 6], all substrings of s[0..6] = "0001111" satisfy the k-constraint except for the substrings s[0..5] = "000111" and s[0..6] = "0001111".
Example 2:
Input: s = "010101", k = 1, queries = [[0,5],[1,4],[2,3]]
Output: [15,9,3]
Explanation:
The substrings of s with a length greater than 3 do not satisfy the k-constraint.
Constraints:
1 <= s.length <= 105s[i] is either '0' or '1'.1 <= k <= s.length1 <= queries.length <= 105queries[i] == [li, ri]0 <= li <= ri < s.lengthProblem summary: 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. Return an integer array answer, where answer[i] is the number of substrings of s[li..ri] that satisfy the k-constraint.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Sliding Window
"0001111" 2 [[0,6]]
"010101" 1 [[0,5],[1,4],[2,3]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3261: Count Substrings That Satisfy K-Constraint II
class Solution {
public long[] countKConstraintSubstrings(String s, int k, int[][] queries) {
int[] cnt = new int[2];
int n = s.length();
int[] d = new int[n];
Arrays.fill(d, n);
long[] pre = new long[n + 1];
for (int i = 0, j = 0; j < n; ++j) {
cnt[s.charAt(j) - '0']++;
while (cnt[0] > k && cnt[1] > k) {
d[i] = j;
cnt[s.charAt(i++) - '0']--;
}
pre[j + 1] = pre[j] + j - i + 1;
}
int m = queries.length;
long[] ans = new long[m];
for (int i = 0; i < m; ++i) {
int l = queries[i][0], r = queries[i][1];
int p = Math.min(r + 1, d[l]);
long a = (1L + p - l) * (p - l) / 2;
long b = pre[r + 1] - pre[p];
ans[i] = a + b;
}
return ans;
}
}
// Accepted solution for LeetCode #3261: Count Substrings That Satisfy K-Constraint II
func countKConstraintSubstrings(s string, k int, queries [][]int) (ans []int64) {
cnt := [2]int{}
n := len(s)
d := make([]int, n)
for i := range d {
d[i] = n
}
pre := make([]int, n+1)
for i, j := 0, 0; j < n; j++ {
cnt[s[j]-'0']++
for cnt[0] > k && cnt[1] > k {
d[i] = j
cnt[s[i]-'0']--
i++
}
pre[j+1] = pre[j] + j - i + 1
}
for _, q := range queries {
l, r := q[0], q[1]
p := min(r+1, d[l])
a := (1 + p - l) * (p - l) / 2
b := pre[r+1] - pre[p]
ans = append(ans, int64(a+b))
}
return
}
# Accepted solution for LeetCode #3261: Count Substrings That Satisfy K-Constraint II
class Solution:
def countKConstraintSubstrings(
self, s: str, k: int, queries: List[List[int]]
) -> List[int]:
cnt = [0, 0]
i, n = 0, len(s)
d = [n] * n
pre = [0] * (n + 1)
for j, x in enumerate(map(int, s)):
cnt[x] += 1
while cnt[0] > k and cnt[1] > k:
d[i] = j
cnt[int(s[i])] -= 1
i += 1
pre[j + 1] = pre[j] + j - i + 1
ans = []
for l, r in queries:
p = min(r + 1, d[l])
a = (1 + p - l) * (p - l) // 2
b = pre[r + 1] - pre[p]
ans.append(a + b)
return ans
// Accepted solution for LeetCode #3261: Count Substrings That Satisfy K-Constraint II
/**
* [3261] Count Substrings That Satisfy K-Constraint II
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn count_k_constraint_substrings(s: String, k: i32, queries: Vec<Vec<i32>>) -> Vec<i64> {
let s: Vec<u32> = s.chars().map(|x| x.to_digit(10).unwrap()).collect();
let n = s.len();
let mut window = (0, 0);
let mut right_array = vec![n; n];
let mut prefix = vec![0; n + 1];
let mut left = 0;
for right in 0..n {
if s[right] == 0 {
window.0 += 1;
} else {
window.1 += 1;
}
while window.0 > k && window.1 > k {
if s[left] == 0 {
window.0 -= 1;
} else {
window.1 -= 1;
}
right_array[left] = right;
left += 1;
}
prefix[right + 1] = prefix[right] + (right - left + 1) as i64;
}
queries
.into_iter()
.map(|query| {
let (l, r) = (query[0] as usize, query[1] as usize);
let min_r = right_array[l].min(r + 1) as i64;
let l = l as i64;
(min_r - l + 1) * (min_r - l) / 2 + prefix[r + 1] - prefix[min_r as usize]
})
.collect()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3261() {
assert_eq!(
vec![26],
Solution::count_k_constraint_substrings("0001111".to_owned(), 2, vec![vec![0, 6]])
);
assert_eq!(
vec![15, 9, 3],
Solution::count_k_constraint_substrings(
"010101".to_owned(),
1,
vec![vec![0, 5], vec![1, 4], vec![2, 3]]
)
);
assert_eq!(
vec![1, 3, 1],
Solution::count_k_constraint_substrings(
"00".to_owned(),
1,
vec![vec![0, 0], vec![0, 1], vec![1, 1]]
)
);
}
}
// Accepted solution for LeetCode #3261: Count Substrings That Satisfy K-Constraint II
function countKConstraintSubstrings(s: string, k: number, queries: number[][]): number[] {
const cnt: [number, number] = [0, 0];
const n = s.length;
const d: number[] = Array(n).fill(n);
const pre: number[] = Array(n + 1).fill(0);
for (let i = 0, j = 0; j < n; ++j) {
cnt[+s[j]]++;
while (Math.min(cnt[0], cnt[1]) > k) {
d[i] = j;
cnt[+s[i++]]--;
}
pre[j + 1] = pre[j] + j - i + 1;
}
const ans: number[] = [];
for (const [l, r] of queries) {
const p = Math.min(r + 1, d[l]);
const a = ((1 + p - l) * (p - l)) / 2;
const b = pre[r + 1] - pre[p];
ans.push(a + b);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.