Binary search and search on the answer
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.
How it works
- Invariant: the range must contain the answer; each comparison drops the half that can't.
bisect_leftfinds the first>= x,bisect_rightthe 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)withwhile lo < hiso 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
Solve it in Python 10
- Integer square rooteasy
- Peak of a mountain listeasy
- Find a value in a rotated sorted listmedium
- Find a value in a sorted gridmedium
- First and last index of a valuemedium
- Key-value store with historymedium
- Smallest truck that meets the deadlinemedium
- Widest spacing for k sensorsmedium
- K-th smallest distance among pairshard
- Median across two sorted listshard
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 ofxisupper − 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
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 loReal 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, JavaArrays.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):
insortsearches 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) / 2overflow 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 = midwith a floormidcan loop forever oncehi = lo + 1; round up or uselo = mid + 1.(lo + hi) / 2overflows 32-bit ints in Java/C++; uselo + (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.