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 of length n, where:
'1' represents an active section.'0' represents an inactive section.You can perform at most one trade to maximize the number of active sections in s. In a trade, you:
'1's that is surrounded by '0's to all '0's.'0's that is surrounded by '1's to all '1's.Additionally, you are given a 2D array queries, where queries[i] = [li, ri] represents a substring s[li...ri].
For each query, determine the maximum possible number of active sections in s after making the optimal trade on the substring s[li...ri].
Return an array answer, where answer[i] is the result for queries[i].
Note
s[li...ri] as if it is augmented with a '1' at both ends, forming t = '1' + s[li...ri] + '1'. The augmented '1's do not contribute to the final count.Example 1:
Input: s = "01", queries = [[0,1]]
Output: [1]
Explanation:
Because there is no block of '1's surrounded by '0's, no valid trade is possible. The maximum number of active sections is 1.
Example 2:
Input: s = "0100", queries = [[0,3],[0,2],[1,3],[2,3]]
Output: [4,3,1,1]
Explanation:
Query [0, 3] → Substring "0100" → Augmented to "101001"
Choose "0100", convert "0100" → "0000" → "1111".
The final string without augmentation is "1111". The maximum number of active sections is 4.
Query [0, 2] → Substring "010" → Augmented to "10101"
Choose "010", convert "010" → "000" → "111".
The final string without augmentation is "1110". The maximum number of active sections is 3.
Query [1, 3] → Substring "100" → Augmented to "11001"
Because there is no block of '1's surrounded by '0's, no valid trade is possible. The maximum number of active sections is 1.
Query [2, 3] → Substring "00" → Augmented to "1001"
Because there is no block of '1's surrounded by '0's, no valid trade is possible. The maximum number of active sections is 1.
Example 3:
Input: s = "1000100", queries = [[1,5],[0,6],[0,4]]
Output: [6,7,2]
Explanation:
Query [1, 5] → Substring "00010" → Augmented to "1000101"
Choose "00010", convert "00010" → "00000" → "11111".
The final string without augmentation is "1111110". The maximum number of active sections is 6.
Query [0, 6] → Substring "1000100" → Augmented to "110001001"
Choose "000100", convert "000100" → "000000" → "111111".
The final string without augmentation is "1111111". The maximum number of active sections is 7.
Query [0, 4] → Substring "10001" → Augmented to "1100011"
Because there is no block of '1's surrounded by '0's, no valid trade is possible. The maximum number of active sections is 2.
Example 4:
Input: s = "01010", queries = [[0,3],[1,4],[1,3]]
Output: [4,4,2]
Explanation:
Query [0, 3] → Substring "0101" → Augmented to "101011"
Choose "010", convert "010" → "000" → "111".
The final string without augmentation is "11110". The maximum number of active sections is 4.
Query [1, 4] → Substring "1010" → Augmented to "110101"
Choose "010", convert "010" → "000" → "111".
The final string without augmentation is "01111". The maximum number of active sections is 4.
Query [1, 3] → Substring "101" → Augmented to "11011"
Because there is no block of '1's surrounded by '0's, no valid trade is possible. The maximum number of active sections is 2.
Constraints:
1 <= n == s.length <= 1051 <= queries.length <= 105s[i] is either '0' or '1'.queries[i] = [li, ri]0 <= li <= ri < nProblem summary: You are given a binary string s of length n, where: '1' represents an active section. '0' represents an inactive section. You can perform at most one trade to maximize the number of active sections in s. In a trade, you: Convert a contiguous block of '1's that is surrounded by '0's to all '0's. Afterward, convert a contiguous block of '0's that is surrounded by '1's to all '1's. Additionally, you are given a 2D array queries, where queries[i] = [li, ri] represents a substring s[li...ri]. For each query, determine the maximum possible number of active sections in s after making the optimal trade on the substring s[li...ri]. Return an array answer, where answer[i] is the result for queries[i]. Note For each query, treat s[li...ri] as if it is augmented with a '1' at both ends, forming t = '1' + s[li...ri] + '1'. The augmented '1's do not contribute to the final count. The queries are
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Segment Tree
"01" [[0,1]]
"0100" [[0,3],[0,2],[1,3],[2,3]]
"1000100" [[1,5],[0,6],[0,4]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3501: Maximize Active Section with Trade II
class Group {
public int start;
public int length;
public Group(int start, int length) {
this.start = start;
this.length = length;
}
}
class SparseTable {
public SparseTable(int[] nums) {
n = nums.length;
st = new int[bitLength(n) + 1][n + 1];
System.arraycopy(nums, 0, st[0], 0, n);
for (int i = 1; i <= st.length; ++i)
for (int j = 0; j + (1 << i) <= n; ++j)
st[i][j] = Math.max(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);
}
// Returns max(nums[l..r])
public int query(int l, int r) {
final int i = bitLength(r - l + 1) - 1;
return Math.max(st[i][l], st[i][r - (1 << i) + 1]);
}
private final int n;
private final int[][] st; // st[i][j] := max(nums[j..j + 2^i - 1])
private int bitLength(int n) {
return Integer.SIZE - Integer.numberOfLeadingZeros(n);
}
}
class Solution {
public List<Integer> maxActiveSectionsAfterTrade(String s, int[][] queries) {
final int n = s.length();
final int ones = (int) s.chars().filter(c -> c == '1').count();
final Pair<List<Group>, int[]> zeroGroupsInfo = getZeroGroups(s);
final List<Group> zeroGroups = zeroGroupsInfo.getKey();
final int[] zeroGroupIndex = zeroGroupsInfo.getValue();
if (zeroGroups.isEmpty())
return Collections.nCopies(queries.length, ones);
final SparseTable st = new SparseTable(getZeroMergeLengths(zeroGroups));
final List<Integer> ans = new ArrayList<>();
for (int[] query : queries) {
final int l = query[0];
final int r = query[1];
final int left = zeroGroupIndex[l] == -1 ? -1
: (zeroGroups.get(zeroGroupIndex[l]).length -
(l - zeroGroups.get(zeroGroupIndex[l]).start));
final int right =
zeroGroupIndex[r] == -1 ? -1 : (r - zeroGroups.get(zeroGroupIndex[r]).start + 1);
final Pair<Integer, Integer> adjacentIndices = mapToAdjacentGroupIndices(
zeroGroupIndex[l] + 1, s.charAt(r) == '1' ? zeroGroupIndex[r] : zeroGroupIndex[r] - 1);
final int startAdjacentGroupIndex = adjacentIndices.getKey();
final int endAdjacentGroupIndex = adjacentIndices.getValue();
int activeSections = ones;
if (s.charAt(l) == '0' && s.charAt(r) == '0' && zeroGroupIndex[l] + 1 == zeroGroupIndex[r])
activeSections = Math.max(activeSections, ones + left + right);
else if (startAdjacentGroupIndex <= endAdjacentGroupIndex)
activeSections = Math.max(activeSections,
ones + st.query(startAdjacentGroupIndex, endAdjacentGroupIndex));
if (s.charAt(l) == '0' &&
zeroGroupIndex[l] + 1 <= (s.charAt(r) == '1' ? zeroGroupIndex[r] : zeroGroupIndex[r] - 1))
activeSections =
Math.max(activeSections, ones + left + zeroGroups.get(zeroGroupIndex[l] + 1).length);
if (s.charAt(r) == '0' && zeroGroupIndex[l] < zeroGroupIndex[r] - 1)
activeSections =
Math.max(activeSections, ones + right + zeroGroups.get(zeroGroupIndex[r] - 1).length);
ans.add(activeSections);
}
return ans;
}
// Returns the zero groups and the index of the zero group that contains the i-th character
private Pair<List<Group>, int[]> getZeroGroups(String s) {
final List<Group> zeroGroups = new ArrayList<>();
final int[] zeroGroupIndex = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '0') {
if (i > 0 && s.charAt(i - 1) == '0')
zeroGroups.get(zeroGroups.size() - 1).length++;
else
zeroGroups.add(new Group(i, 1));
}
zeroGroupIndex[i] = zeroGroups.size() - 1;
}
return new Pair<>(zeroGroups, zeroGroupIndex);
}
// Returns the sums of the lengths of the adjacent groups
private int[] getZeroMergeLengths(List<Group> zeroGroups) {
final int[] zeroMergeLengths = new int[zeroGroups.size() - 1];
for (int i = 0; i < zeroGroups.size() - 1; ++i)
zeroMergeLengths[i] = zeroGroups.get(i).length + zeroGroups.get(i + 1).length;
return zeroMergeLengths;
}
// Returns the indices of the adjacent groups that contain l and r completely
private Pair<Integer, Integer> mapToAdjacentGroupIndices(int startGroupIndex, int endGroupIndex) {
return new Pair<>(startGroupIndex, endGroupIndex - 1);
}
}
// Accepted solution for LeetCode #3501: Maximize Active Section with Trade II
package main
import (
"math/bits"
)
// https://space.bilibili.com/206214
type pair struct{ l, r int } // 左闭右开
type ST [][]int
func newST(a []pair) ST {
n := len(a) - 1
sz := bits.Len(uint(n))
st := make(ST, n)
for i, p := range a[:n] {
st[i] = make([]int, sz)
st[i][0] = p.r - p.l + a[i+1].r - a[i+1].l
}
for j := 1; j < sz; j++ {
for i := 0; i+1<<j <= n; i++ {
st[i][j] = max(st[i][j-1], st[i+1<<(j-1)][j-1])
}
}
return st
}
// 查询区间最大值,[l,r) 左闭右开
func (st ST) query(l, r int) int {
if l >= r {
return 0
}
k := bits.Len(uint(r-l)) - 1
return max(st[l][k], st[r-1<<k][k])
}
func maxActiveSectionsAfterTrade(s string, queries [][]int) []int {
n := len(s)
total1 := 0
belong := make([]int, n) // 每个 0 所属的区间下标,每个 1 右边最近的 0 区间下标
a := []pair{{-1, -1}}
start := 0
for i, b := range s {
belong[i] = len(a)
if i == n-1 || byte(b) != s[i+1] {
if s[i] == '1' {
total1 += i - start + 1
} else {
a = append(a, pair{start, i + 1})
}
start = i + 1
}
}
a = append(a, pair{n + 1, n + 1})
merge := func(x, y int) int {
if x > 0 && y > 0 {
return x + y
}
return 0
}
st := newST(a)
ans := make([]int, len(queries))
for qi, q := range queries {
ql, qr := q[0], q[1]
i := belong[ql]
if ql > 0 && s[ql] == '0' && s[ql-1] == '0' {
i++ // i 在残缺区间中
}
j := belong[qr] - 1
if qr+1 < n && s[qr] == '0' && s[qr+1] == '1' {
j++ // j 刚好在完整区间的右端点,无需减一
}
qr++
mx := 0
if i <= j {
mx = max(
st.query(i, j),
merge(a[i-1].r-ql, a[i].r-a[i].l),
merge(qr-a[j+1].l, a[j].r-a[j].l),
)
} else if i == j+1 {
mx = merge(a[i-1].r-ql, qr-a[j+1].l)
}
ans[qi] = total1 + mx
}
return ans
}
# Accepted solution for LeetCode #3501: Maximize Active Section with Trade II
from dataclasses import dataclass
@dataclass
class Group:
start: int
length: int
class SparseTable:
def __init__(self, nums: list[int]):
self.n = len(nums)
# st[i][j] := max(nums[j..j + 2^i - 1])
self.st = [[0] * (self.n + 1) for _ in range(self.n.bit_length() + 1)]
self.st[0] = nums.copy()
for i in range(1, self.n.bit_length() + 1):
for j in range(self.n - (1 << i) + 1):
self.st[i][j] = max(
self.st[i - 1][j],
self.st[i - 1][j + (1 << (i - 1))])
def query(self, l: int, r: int) -> int:
"""Returns max(nums[l..r])."""
i = (r - l + 1).bit_length() - 1
return max(self.st[i][l], self.st[i][r - (1 << i) + 1])
class Solution:
def maxActiveSectionsAfterTrade(
self,
s: str,
queries: list[list[int]]
) -> list[int]:
ones = s.count('1')
zeroGroups, zeroGroupIndex = self._getZeroGroups(s)
if not zeroGroups:
return [ones] * len(queries)
st = SparseTable(self._getZeroMergeLengths(zeroGroups))
def getMaxActiveSections(l: int, r: int) -> int:
left = (-1 if zeroGroupIndex[l] == -1
else (zeroGroups[zeroGroupIndex[l]].length -
(l - zeroGroups[zeroGroupIndex[l]].start)))
right = (-1 if zeroGroupIndex[r] == -1
else (r - zeroGroups[zeroGroupIndex[r]].start + 1))
startAdjacentGroupIndex, endAdjacentGroupIndex = self._mapToAdjacentGroupIndices(
zeroGroupIndex[l] + 1, zeroGroupIndex[r] if s[r] == '1' else zeroGroupIndex[r] - 1)
activeSections = ones
if (s[l] == '0' and s[r] == '0' and
zeroGroupIndex[l] + 1 == zeroGroupIndex[r]):
activeSections = max(activeSections, ones + left + right)
elif startAdjacentGroupIndex <= endAdjacentGroupIndex:
activeSections = max(
activeSections,
ones + st.query(startAdjacentGroupIndex, endAdjacentGroupIndex))
if (s[l] == '0' and
zeroGroupIndex[l] + 1 <= (zeroGroupIndex[r]
if s[r] == '1' else zeroGroupIndex[r] - 1)):
activeSections = max(activeSections, ones + left +
zeroGroups[zeroGroupIndex[l] + 1].length)
if (s[r] == '0' and zeroGroupIndex[l] < zeroGroupIndex[r] - 1):
activeSections = max(activeSections, ones + right +
zeroGroups[zeroGroupIndex[r] - 1].length)
return activeSections
return [getMaxActiveSections(l, r) for l, r in queries]
def _getZeroGroups(self, s: str) -> tuple[list[Group], list[int]]:
"""
Returns the zero groups and the index of the zero group that contains the
i-th character.
"""
zeroGroups = []
zeroGroupIndex = []
for i in range(len(s)):
if s[i] == '0':
if i > 0 and s[i - 1] == '0':
zeroGroups[-1].length += 1
else:
zeroGroups.append(Group(i, 1))
zeroGroupIndex.append(len(zeroGroups) - 1)
return zeroGroups, zeroGroupIndex
def _getZeroMergeLengths(self, zeroGroups: list[Group]) -> list[int]:
"""Returns the sums of the lengths of the adjacent groups."""
return [a.length + b.length for a, b in itertools.pairwise(zeroGroups)]
def _mapToAdjacentGroupIndices(
self,
startGroupIndex: int,
endGroupIndex: int
) -> tuple[int, int]:
"""
Returns the indices of the adjacent groups that contain l and r completely.
e.g. groupIndices = [0, 1, 2, 3]
adjacentGroupIndices = [0 (0, 1), 1 (1, 2), 2 (2, 3)]
map(startGroupIndex = 1, endGroupIndex = 3) -> (1, 2)
"""
return startGroupIndex, endGroupIndex - 1
// Accepted solution for LeetCode #3501: Maximize Active Section with Trade 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 #3501: Maximize Active Section with Trade II
// class Group {
// public int start;
// public int length;
// public Group(int start, int length) {
// this.start = start;
// this.length = length;
// }
// }
//
// class SparseTable {
// public SparseTable(int[] nums) {
// n = nums.length;
// st = new int[bitLength(n) + 1][n + 1];
// System.arraycopy(nums, 0, st[0], 0, n);
// for (int i = 1; i <= st.length; ++i)
// for (int j = 0; j + (1 << i) <= n; ++j)
// st[i][j] = Math.max(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);
// }
//
// // Returns max(nums[l..r])
// public int query(int l, int r) {
// final int i = bitLength(r - l + 1) - 1;
// return Math.max(st[i][l], st[i][r - (1 << i) + 1]);
// }
//
// private final int n;
// private final int[][] st; // st[i][j] := max(nums[j..j + 2^i - 1])
//
// private int bitLength(int n) {
// return Integer.SIZE - Integer.numberOfLeadingZeros(n);
// }
// }
//
// class Solution {
// public List<Integer> maxActiveSectionsAfterTrade(String s, int[][] queries) {
// final int n = s.length();
// final int ones = (int) s.chars().filter(c -> c == '1').count();
// final Pair<List<Group>, int[]> zeroGroupsInfo = getZeroGroups(s);
// final List<Group> zeroGroups = zeroGroupsInfo.getKey();
// final int[] zeroGroupIndex = zeroGroupsInfo.getValue();
//
// if (zeroGroups.isEmpty())
// return Collections.nCopies(queries.length, ones);
//
// final SparseTable st = new SparseTable(getZeroMergeLengths(zeroGroups));
// final List<Integer> ans = new ArrayList<>();
//
// for (int[] query : queries) {
// final int l = query[0];
// final int r = query[1];
// final int left = zeroGroupIndex[l] == -1 ? -1
// : (zeroGroups.get(zeroGroupIndex[l]).length -
// (l - zeroGroups.get(zeroGroupIndex[l]).start));
// final int right =
// zeroGroupIndex[r] == -1 ? -1 : (r - zeroGroups.get(zeroGroupIndex[r]).start + 1);
// final Pair<Integer, Integer> adjacentIndices = mapToAdjacentGroupIndices(
// zeroGroupIndex[l] + 1, s.charAt(r) == '1' ? zeroGroupIndex[r] : zeroGroupIndex[r] - 1);
// final int startAdjacentGroupIndex = adjacentIndices.getKey();
// final int endAdjacentGroupIndex = adjacentIndices.getValue();
//
// int activeSections = ones;
// if (s.charAt(l) == '0' && s.charAt(r) == '0' && zeroGroupIndex[l] + 1 == zeroGroupIndex[r])
// activeSections = Math.max(activeSections, ones + left + right);
// else if (startAdjacentGroupIndex <= endAdjacentGroupIndex)
// activeSections = Math.max(activeSections,
// ones + st.query(startAdjacentGroupIndex, endAdjacentGroupIndex));
// if (s.charAt(l) == '0' &&
// zeroGroupIndex[l] + 1 <= (s.charAt(r) == '1' ? zeroGroupIndex[r] : zeroGroupIndex[r] - 1))
// activeSections =
// Math.max(activeSections, ones + left + zeroGroups.get(zeroGroupIndex[l] + 1).length);
// if (s.charAt(r) == '0' && zeroGroupIndex[l] < zeroGroupIndex[r] - 1)
// activeSections =
// Math.max(activeSections, ones + right + zeroGroups.get(zeroGroupIndex[r] - 1).length);
// ans.add(activeSections);
// }
//
// return ans;
// }
//
// // Returns the zero groups and the index of the zero group that contains the i-th character
// private Pair<List<Group>, int[]> getZeroGroups(String s) {
// final List<Group> zeroGroups = new ArrayList<>();
// final int[] zeroGroupIndex = new int[s.length()];
//
// for (int i = 0; i < s.length(); i++) {
// if (s.charAt(i) == '0') {
// if (i > 0 && s.charAt(i - 1) == '0')
// zeroGroups.get(zeroGroups.size() - 1).length++;
// else
// zeroGroups.add(new Group(i, 1));
// }
// zeroGroupIndex[i] = zeroGroups.size() - 1;
// }
//
// return new Pair<>(zeroGroups, zeroGroupIndex);
// }
//
// // Returns the sums of the lengths of the adjacent groups
// private int[] getZeroMergeLengths(List<Group> zeroGroups) {
// final int[] zeroMergeLengths = new int[zeroGroups.size() - 1];
// for (int i = 0; i < zeroGroups.size() - 1; ++i)
// zeroMergeLengths[i] = zeroGroups.get(i).length + zeroGroups.get(i + 1).length;
// return zeroMergeLengths;
// }
//
// // Returns the indices of the adjacent groups that contain l and r completely
// private Pair<Integer, Integer> mapToAdjacentGroupIndices(int startGroupIndex, int endGroupIndex) {
// return new Pair<>(startGroupIndex, endGroupIndex - 1);
// }
// }
// Accepted solution for LeetCode #3501: Maximize Active Section with Trade II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3501: Maximize Active Section with Trade II
// class Group {
// public int start;
// public int length;
// public Group(int start, int length) {
// this.start = start;
// this.length = length;
// }
// }
//
// class SparseTable {
// public SparseTable(int[] nums) {
// n = nums.length;
// st = new int[bitLength(n) + 1][n + 1];
// System.arraycopy(nums, 0, st[0], 0, n);
// for (int i = 1; i <= st.length; ++i)
// for (int j = 0; j + (1 << i) <= n; ++j)
// st[i][j] = Math.max(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);
// }
//
// // Returns max(nums[l..r])
// public int query(int l, int r) {
// final int i = bitLength(r - l + 1) - 1;
// return Math.max(st[i][l], st[i][r - (1 << i) + 1]);
// }
//
// private final int n;
// private final int[][] st; // st[i][j] := max(nums[j..j + 2^i - 1])
//
// private int bitLength(int n) {
// return Integer.SIZE - Integer.numberOfLeadingZeros(n);
// }
// }
//
// class Solution {
// public List<Integer> maxActiveSectionsAfterTrade(String s, int[][] queries) {
// final int n = s.length();
// final int ones = (int) s.chars().filter(c -> c == '1').count();
// final Pair<List<Group>, int[]> zeroGroupsInfo = getZeroGroups(s);
// final List<Group> zeroGroups = zeroGroupsInfo.getKey();
// final int[] zeroGroupIndex = zeroGroupsInfo.getValue();
//
// if (zeroGroups.isEmpty())
// return Collections.nCopies(queries.length, ones);
//
// final SparseTable st = new SparseTable(getZeroMergeLengths(zeroGroups));
// final List<Integer> ans = new ArrayList<>();
//
// for (int[] query : queries) {
// final int l = query[0];
// final int r = query[1];
// final int left = zeroGroupIndex[l] == -1 ? -1
// : (zeroGroups.get(zeroGroupIndex[l]).length -
// (l - zeroGroups.get(zeroGroupIndex[l]).start));
// final int right =
// zeroGroupIndex[r] == -1 ? -1 : (r - zeroGroups.get(zeroGroupIndex[r]).start + 1);
// final Pair<Integer, Integer> adjacentIndices = mapToAdjacentGroupIndices(
// zeroGroupIndex[l] + 1, s.charAt(r) == '1' ? zeroGroupIndex[r] : zeroGroupIndex[r] - 1);
// final int startAdjacentGroupIndex = adjacentIndices.getKey();
// final int endAdjacentGroupIndex = adjacentIndices.getValue();
//
// int activeSections = ones;
// if (s.charAt(l) == '0' && s.charAt(r) == '0' && zeroGroupIndex[l] + 1 == zeroGroupIndex[r])
// activeSections = Math.max(activeSections, ones + left + right);
// else if (startAdjacentGroupIndex <= endAdjacentGroupIndex)
// activeSections = Math.max(activeSections,
// ones + st.query(startAdjacentGroupIndex, endAdjacentGroupIndex));
// if (s.charAt(l) == '0' &&
// zeroGroupIndex[l] + 1 <= (s.charAt(r) == '1' ? zeroGroupIndex[r] : zeroGroupIndex[r] - 1))
// activeSections =
// Math.max(activeSections, ones + left + zeroGroups.get(zeroGroupIndex[l] + 1).length);
// if (s.charAt(r) == '0' && zeroGroupIndex[l] < zeroGroupIndex[r] - 1)
// activeSections =
// Math.max(activeSections, ones + right + zeroGroups.get(zeroGroupIndex[r] - 1).length);
// ans.add(activeSections);
// }
//
// return ans;
// }
//
// // Returns the zero groups and the index of the zero group that contains the i-th character
// private Pair<List<Group>, int[]> getZeroGroups(String s) {
// final List<Group> zeroGroups = new ArrayList<>();
// final int[] zeroGroupIndex = new int[s.length()];
//
// for (int i = 0; i < s.length(); i++) {
// if (s.charAt(i) == '0') {
// if (i > 0 && s.charAt(i - 1) == '0')
// zeroGroups.get(zeroGroups.size() - 1).length++;
// else
// zeroGroups.add(new Group(i, 1));
// }
// zeroGroupIndex[i] = zeroGroups.size() - 1;
// }
//
// return new Pair<>(zeroGroups, zeroGroupIndex);
// }
//
// // Returns the sums of the lengths of the adjacent groups
// private int[] getZeroMergeLengths(List<Group> zeroGroups) {
// final int[] zeroMergeLengths = new int[zeroGroups.size() - 1];
// for (int i = 0; i < zeroGroups.size() - 1; ++i)
// zeroMergeLengths[i] = zeroGroups.get(i).length + zeroGroups.get(i + 1).length;
// return zeroMergeLengths;
// }
//
// // Returns the indices of the adjacent groups that contain l and r completely
// private Pair<Integer, Integer> mapToAdjacentGroupIndices(int startGroupIndex, int endGroupIndex) {
// return new Pair<>(startGroupIndex, endGroupIndex - 1);
// }
// }
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.