Data Structures and Algorithms5 min read

Binary Search on the Answer Space: Eliminating Off-by-One Bugs

How to recognize monotonic feasibility predicates in interview prompts, lock down your binary search loop invariant so off-by-one bugs disappear, and use Python's bisect module effectively.

Binary search on the answer applies whenever a problem asks for the minimum feasible threshold or maximum achievable cap and validity changes monotonically across the candidate range. Keeping lo on the infeasible side or looping while lo < hi with hi = mid guarantees convergence on the exact transition boundary without off-by-one ambiguity.

Key takeaways

  • Separate searching an input array from searching a numeric decision space using a greedy checker.
  • Define exact boundary invariants before writing the loop condition.
  • Verify tight bounds: max(weights) to sum(weights) prevents impossible mid candidates.

Quick facts

  • Any optimization prompt asking for a minimum feasible limit or minimax bound often hides a monotonic predicate.
  • Using lo < hi with hi = mid when feasible(mid) is true shrinks the candidate interval until lo == hi.
  • Upper-bound binary search targeting maximum feasibility must shift mid upward using (lo + hi + 1) // 2.
  • Python's bisect module handles sorted array insertion points in O(log n) using __lt__ comparisons.

Recognizing Hidden Binary Search Prompts

When candidates hear "binary search," most look for a sorted array in the input. As highlighted in the Ace Hired roadmap guide, binary search variants remain one of the most frequent failure clusters in technical screens precisely because the input array itself is often unsorted.

The telltale phrasing is optimization under a constraint: "find the minimum speed to finish within HH hours," "minimize the largest subarray sum across KK splits," or "maximize the minimum distance between CC stalls." Whenever checking whether a guessed answer xx works is much faster than finding xx directly, you are looking at binary search on the answer space.

Monotonic boolean predicate boundary for binary search on the answer space
Monotonic boolean predicate boundary for binary search on the answer space

Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).

The Loop Invariant That Kills Off-by-One Bugs

1. Monotonicity over the candidate domain

Suppose every candidate answer xx in [L,R][L, R] yields a boolean verdict feasible(x). If making xx larger never breaks feasibility, the predicate produces a clean sequence of False values followed by True values.

As CP-Algorithms notes on predicate binary search, once you have a monotonic function, binary search locates the unique transition index in O(log⁡(R−L))O(\log(R - L)) predicate evaluations.

2. Lower-bound vs. upper-bound midpoint rules

I never guess between lo <= hi and lo < hi. Instead, I commit to one exact loop invariant for finding the first `True` value (minimum feasible answer):

  1. Initialize lo and hi so the true answer is guaranteed to lie inside [lo, hi].
  2. Loop while lo < hi: mid = lo + (hi - lo) // 2 rounds down, so mid < hi always holds.
  3. If feasible(mid) is True, mid could be the answer, so set hi = mid.
  4. Otherwise mid is impossible, so exclude it with lo = mid + 1.

When lo == hi, the loop exits and lo is the minimum valid answer. What if you instead need the last `True` value (maximum valid cap, such as maximizing minimum spacing)? Flip the update to keep mid on lo = mid and set hi = mid - 1 when invalid, but change mid to (lo + hi + 1) // 2 so lo = mid never stalls in an infinite two-element loop.

What about continuous search over real numbers, such as cutting wooden ribbons or finding square roots to tolerance δ\delta? Instead of writing while hi - lo > 1e-7, which can spin forever under floating-point precision loss when magnitudes grow large, I run a fixed count of 80 bisection iterations (for _ in range(80):). Since 2−80<10−242^{-80} < 10^{-24}, fixed iterations shrink any interval below IEEE 754 precision cleanly in constant time without infinite-loop risk.

Binary search also adapts cleanly to rotated sorted arrays, where one half around mid is always monotonically sorted (nums[lo] <= nums[mid] tells you the left side is sorted). Once you identify which half is ordered, checking whether target sits inside that ordered range tells you which half to discard in O(log⁡n)O(\log n).

Binary search iterations narrowing ship capacity range on weights 1,2,3,4,5
Binary search iterations narrowing ship capacity range on weights 1,2,3,4,5

Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).

Working Python Code

Below are two complete implementations: minimum ship capacity over sequential days (min_ship_capacity), and maximum minimum spacing across sorted positions (max_min_distance), showing both lower-bound and upper-bound invariants side by side.

PYTHON
from bisect import bisect_left


def min_ship_capacity(weights: list[int], days: int) -> int:
    def feasible(cap: int) -> bool:
        used_days = 1
        current = 0
        for w in weights:
            if current + w > cap:
                used_days += 1
                current = 0
            current += w
        return used_days <= days

    lo, hi = max(weights), sum(weights)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if feasible(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo


def max_min_distance(positions: list[int], count: int) -> int:
    pts = sorted(positions)

    def can_place(gap: int) -> bool:
        placed = 1
        last = pts[0]
        for x in pts[1:]:
            if x - last >= gap:
                placed += 1
                last = x
                if placed >= count:
                    return True
        return False

    lo, hi = 1, pts[-1] - pts[0]
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if can_place(mid):
            lo = mid
        else:
            hi = mid - 1
    return lo


if __name__ == "__main__":
    assert min_ship_capacity([1, 2, 3, 4, 5], 3) == 6
    assert min_ship_capacity([3, 2, 2, 4, 1, 4], 3) == 6
    assert max_min_distance([1, 2, 8, 4, 9], 3) == 3
    sorted_vals = [10, 20, 20, 35]
    assert bisect_left(sorted_vals, 20) == 1
    print("min_ship_capacity:", min_ship_capacity([1, 2, 3, 4, 5], 3))
    print("max_min_distance:", max_min_distance([1, 2, 8, 4, 9], 3))

Running this script confirms:

TEXT
min_ship_capacity: 6
max_min_distance: 3

For classic array insertion searches, I prefer the standard library instead of hand-rolling loops: Python's `bisect` module provides bisect_left and bisect_right in O(log⁡n)O(\log n) comparisons (using __lt__ exclusively). Note that bisect does support a key parameter since Python 3.10, though searching a range of integers without allocating a sequence still uses the explicit loop above.

Complexity Analysis

Let nn be the input length and UU be the numeric span hi - lo of candidate answers:

  • Time complexity: O(nlog⁡U)O(n \log U), because each of the ⌈log⁡2(U+1)⌉\lceil \log_2(U + 1) \rceil bisection steps evaluates a greedy linear checker in O(n)O(n). For max_min_distance, initial sorting adds O(nlog⁡n)O(n \log n) once before the loop.
  • Auxiliary space: O(1)O(1) for min_ship_capacity since the greedy scan uses scalar counters; O(n)O(n) if sorting a copy of input coordinates.

Even when UU reaches 10910^9, log⁡2(109)≈30\log_2(10^9) \approx 30 iterations, so the multiplier stays small enough to pass strict interview constraints effortlessly.

Four edge bugs show up repeatedly during whiteboard checks:

  • Picking invalid initial bounds: Setting lo = 1 instead of max(weights) allows feasible(mid) to break silently or accept partial items when an item exceeds mid.
  • Infinite two-element loop on upper bound: Writing mid = (lo + hi) // 2 together with lo = mid hangs forever once hi == lo + 1.
  • Breaking greedy order: In shipping or painter-partition problems, items cannot be reordered; sorting weights corrupts the problem completely.
  • Assuming `bisect.insort` is $O(\log n)$: As the Python documentation warns, locating the index takes O(log⁡n)O(\log n), yet list insertion shifts elements in O(n)O(n).

I skip binary search on the answer whenever the decision predicate is non-monotonic (for instance, convex valleys where ternary search or calculus applies, or subarrays with negative elements where feasibility flickers True and False). If checking feasibility requires exponential backtracking, binary search around it rarely helps either.

Practice Problems

Test both invariant directions on these two benchmark problems:

  1. Koko Eating Bananas: Practice lower-bound answer search with integer ceiling division ((p + speed - 1) // speed).
  2. Capacity To Ship Packages Within D Days: Practice tight initial bounds [max(weights), sum(weights)] and greedy partition validation.

Sources