Binary search and search on the answer

In one sentence

Halve a sorted range each step to find a value, or the first point where a monotonic yes/no predicate flips, in O(log n) checks: ~30 even for a 10⁹-wide answer space.

Analogy: Guessing a number from 1 to 100 with "higher" or "lower" hints: always guess the middle and you need at most 7 guesses.

Find the first value where the predicate turns true: keep mid when it passes, discard it when it fails. Both branches shrink the range, so the loop ends.

How it works

  • Invariant: the range must contain the answer; each comparison drops the half that can't.
  • bisect_left finds the first >= x, bisect_right the first > x; their difference counts x.
  • Search on the answer: binary search a capacity or time, checking feasibility at each step.
  • Check monotonicity first: if capacity c works, c + 1 must work too.
  • Use half-open [lo, hi) with while lo < hi so every branch shrinks the range.

Check yourself

Answer to mark it learned; your answers aren't scored.

Find the minimum eating speed that finishes all banana piles within H hours. Hours needed fall as speed rises. Brute force tries every speed up to max(pile). Best approach?

Go deeper

Loops in motion Interactive labBig-O growth Interactive lab
Solve it in Python 10
Full explanation

Binary search keeps a range that must contain the answer and halves it each step: O(log n).

The robust form searches for a boundary, not a value. Define a monotonic predicate ok(x) (false, false, …, true, true) and find the first true:

  • Lower bound: first index with a[i] >= x (bisect_left).
  • Upper bound: first index with a[i] > x (bisect_right). The count of x is upper − lower.

Search on the answer: when the question is "the minimum capacity, speed or time that is feasible", binary search the value and check feasibility, often greedily. Shipping packages within D days: ok(cap) simulates loading in O(n), and caps range from max(w) to sum(w), so O(n log(sum)).

Write it with a half-open range [lo, hi) and while lo < hi, and decide before coding what lo means when the loop ends. Rotated arrays and peak finding work too, as long as one comparison tells you which half to drop.

Code Lower bound and search on the answer
pythonLower bound and search on the answer
def lower_bound(a: list[int], x: int) -> int:
    """First index i with a[i] >= x, or len(a). Same as bisect.bisect_left."""
    lo, hi = 0, len(a)                 # half-open [lo, hi)
    while lo < hi:
        mid = (lo + hi) // 2           # no overflow in Python; in Java/C++ use lo + (hi - lo) / 2
        if a[mid] < x:
            lo = mid + 1               # mid and everything left of it are too small
        else:
            hi = mid                   # mid might be the answer: keep it
    return lo

def min_ship_capacity(weights: list[int], days: int) -> int:
    def feasible(cap: int) -> bool:    # monotonic: if cap works, cap + 1 works
        used, load = 1, 0
        for w in weights:
            if load + w > cap:
                used, load = used + 1, 0
            load += w
        return used <= days

    lo, hi = max(weights), sum(weights)  # below max(w) the check would lie
    while lo < hi:
        mid = (lo + hi) // 2
        if feasible(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo
Real example

Ship packages within D days: weights 1 to 10 (sum 55), D = 5. Capacity lies in [10, 55]. Checks: 32 yes, 21 yes, 15 yes ([1–5], [6, 7], [8], [9], [10] = 5 days), 12 no, 14 no. Answer: 15, after 5 feasibility checks instead of trying up to 46 capacities.

Trade-offs +3 · −3

+ You gain

  • O(log n): ~30 steps cover 10⁹ values.
  • Turns "find the minimum X that works" into a series of yes/no checks.
  • Built in: Python bisect, C++ lower_bound/upper_bound, Java Arrays.binarySearch.

− You pay

  • Needs sorted data or a provably monotonic predicate; otherwise it returns wrong answers silently.
  • Off-by-one and infinite-loop bugs are notorious.
  • Inserting into a sorted Python list is still O(n): insort searches fast but shifts elements.

Use it when

Sorted arrays, first or last occurrence, "minimum or maximum X such that…" with a monotonic feasibility check, rotated arrays, and huge numeric answer ranges.

Avoid it when

Unsorted data searched once (a linear scan beats sorting), non-monotonic predicates, or frequent inserts into a sorted list: use a heap or a balanced tree.

Numbers to know 4
  • log₂(10⁶) ≈ 20 and log₂(10⁹) ≈ 30 iterations.
  • Search on the answer costs O(log(range) × cost of one check), e.g. O(n log(sum)).
  • The (low + high) / 2 overflow bug sat in the JDK's binary search ~9 years before it was reported (Bloch, 2006).
  • That bug needs low + high > 2³¹ − 1: arrays of 2³⁰ (~1 billion) elements or more.
Common pitfalls 4
  • lo = mid with a floor mid can loop forever once hi = lo + 1; round up or use lo = mid + 1.
  • (lo + hi) / 2 overflows 32-bit ints in Java/C++; use lo + (hi - lo) / 2.
  • Bounds that let the check lie: with capacity below max(w), the greedy check "fits" a package that can't fit.
  • A non-monotonic predicate: you get a wrong answer, not an error.
Interview questions 2

Answer out loud first, then reveal.

How do you recognize binary search on the answer?Show answer

The question asks for a minimum or maximum value (capacity, speed, time, distance) and checking whether a given value works is easy, often a greedy O(n) pass. Then I verify monotonicity: if capacity c works, does c + 1? If yes, I binary search between a low bound and a surely feasible high bound, for O(n log range). Eating speed, shipping within D days and splitting an array to minimize the largest sum are all this.

How do you avoid off-by-one errors in binary search?Show answer

I always search for a boundary with one template: half-open [lo, hi), while lo < hi, mid = (lo + hi) // 2, then either lo = mid + 1 or hi = mid. Since lo ≤ mid < hi, both branches shrink the range, so it terminates, and lo ends at the first index where the predicate is true. I state the invariant aloud and test empty, one element, all-false and all-true inputs.