Boundary update without `+1` / `-1`
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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given a binary string s of length n and an integer numOps.
You are allowed to perform the following operation on s at most numOps times:
i (where 0 <= i < n) and flip s[i]. If s[i] == '1', change s[i] to '0' and vice versa.You need to minimize the length of the longest substring of s such that all the characters in the substring are identical.
Return the minimum length after the operations.
Example 1:
Input: s = "000001", numOps = 1
Output: 2
Explanation:
By changing s[2] to '1', s becomes "001001". The longest substrings with identical characters are s[0..1] and s[3..4].
Example 2:
Input: s = "0000", numOps = 2
Output: 1
Explanation:
By changing s[0] and s[2] to '1', s becomes "1010".
Example 3:
Input: s = "0101", numOps = 0
Output: 1
Constraints:
1 <= n == s.length <= 105s consists only of '0' and '1'.0 <= numOps <= nProblem summary: You are given a binary string s of length n and an integer numOps. You are allowed to perform the following operation on s at most numOps times: Select any index i (where 0 <= i < n) and flip s[i]. If s[i] == '1', change s[i] to '0' and vice versa. You need to minimize the length of the longest substring of s such that all the characters in the substring are identical. Return the minimum length after the operations.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Binary Search
"000001" 1
"0000" 2
"0101" 0
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3399: Smallest Substring With Identical Characters II
class Solution {
private char[] s;
private int numOps;
public int minLength(String s, int numOps) {
this.numOps = numOps;
this.s = s.toCharArray();
int l = 1, r = s.length();
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
private boolean check(int m) {
int cnt = 0;
if (m == 1) {
char[] t = {'0', '1'};
for (int i = 0; i < s.length; ++i) {
if (s[i] == t[i & 1]) {
++cnt;
}
}
cnt = Math.min(cnt, s.length - cnt);
} else {
int k = 0;
for (int i = 0; i < s.length; ++i) {
++k;
if (i == s.length - 1 || s[i] != s[i + 1]) {
cnt += k / (m + 1);
k = 0;
}
}
}
return cnt <= numOps;
}
}
// Accepted solution for LeetCode #3399: Smallest Substring With Identical Characters II
func minLength(s string, numOps int) int {
check := func(m int) bool {
m++
cnt := 0
if m == 1 {
t := "01"
for i := range s {
if s[i] == t[i&1] {
cnt++
}
}
cnt = min(cnt, len(s)-cnt)
} else {
k := 0
for i := range s {
k++
if i == len(s)-1 || s[i] != s[i+1] {
cnt += k / (m + 1)
k = 0
}
}
}
return cnt <= numOps
}
return 1 + sort.Search(len(s), func(m int) bool { return check(m) })
}
# Accepted solution for LeetCode #3399: Smallest Substring With Identical Characters II
class Solution:
def minLength(self, s: str, numOps: int) -> int:
def check(m: int) -> bool:
cnt = 0
if m == 1:
t = "01"
cnt = sum(c == t[i & 1] for i, c in enumerate(s))
cnt = min(cnt, n - cnt)
else:
k = 0
for i, c in enumerate(s):
k += 1
if i == len(s) - 1 or c != s[i + 1]:
cnt += k // (m + 1)
k = 0
return cnt <= numOps
n = len(s)
return bisect_left(range(n), True, lo=1, key=check)
// Accepted solution for LeetCode #3399: Smallest Substring With Identical Characters II
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3399: Smallest Substring With Identical Characters II
// class Solution {
// private char[] s;
// private int numOps;
//
// public int minLength(String s, int numOps) {
// this.numOps = numOps;
// this.s = s.toCharArray();
// int l = 1, r = s.length();
// while (l < r) {
// int mid = (l + r) >> 1;
// if (check(mid)) {
// r = mid;
// } else {
// l = mid + 1;
// }
// }
// return l;
// }
//
// private boolean check(int m) {
// int cnt = 0;
// if (m == 1) {
// char[] t = {'0', '1'};
// for (int i = 0; i < s.length; ++i) {
// if (s[i] == t[i & 1]) {
// ++cnt;
// }
// }
// cnt = Math.min(cnt, s.length - cnt);
// } else {
// int k = 0;
// for (int i = 0; i < s.length; ++i) {
// ++k;
// if (i == s.length - 1 || s[i] != s[i + 1]) {
// cnt += k / (m + 1);
// k = 0;
// }
// }
// }
// return cnt <= numOps;
// }
// }
// Accepted solution for LeetCode #3399: Smallest Substring With Identical Characters II
function minLength(s: string, numOps: number): number {
const n = s.length;
const check = (m: number): boolean => {
let cnt = 0;
if (m === 1) {
const t = '01';
for (let i = 0; i < n; ++i) {
if (s[i] === t[i & 1]) {
++cnt;
}
}
cnt = Math.min(cnt, n - cnt);
} else {
let k = 0;
for (let i = 0; i < n; ++i) {
++k;
if (i === n - 1 || s[i] !== s[i + 1]) {
cnt += Math.floor(k / (m + 1));
k = 0;
}
}
}
return cnt <= numOps;
};
let [l, r] = [1, n];
while (l < r) {
const mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
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: 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.