Overview
Curated: · Written: · Reviewed:
Binary Search
In one line
Binary search finds the boundary where a monotone yes/no predicate first becomes true, halving the range on each probe, so a sorted array or an answer space of size N takes about log2(N) probes. Reach for it when the question is where something first becomes true, or when the data is static and sorted, not for a single lookup on unsorted data.
Key definitions
- Monotone predicate: false for a prefix of the domain and true for the rest. The search needs exactly one flip.
- Containment invariant: if the answer exists, it lies inside the current range, and every branch must keep that true.
- Half-open range: [lo, hi) with hi exclusive. The loop runs while lo < hi and returns lo, the insertion point.
- Leftmost and rightmost boundary: equality sends the search left (lower bound) or right (upper bound) to find the edge of a run of duplicates.
- Answer-space search: binary search over candidate answers, each candidate checked by a feasibility function.
Formulas and complexity
For n = 1,000,000 that is 20; for n = 2^30 it is 30. Doubling the input adds one probe.
Capacity search with an O(n) feasibility check costs O(n log(sum)). Counting equal elements with two boundary searches costs O(log n), with no scan of the run. Rotated array with duplicates: worst case O(n).
How it works
Each probe evaluates the predicate at mid. True means the answer is at mid or left of it, so hi = mid. False means the answer lies right of mid, so lo = mid + 1. The loop ends when lo == hi, and lo is the answer. Every update must strictly shrink the range, or the loop can revisit the same state forever. Compute the midpoint as lo + (hi - lo) // 2 so it cannot overflow in fixed-width integers.
lo, hi = 0, len(a) # half-open
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] < x: lo = mid + 1
else: hi = mid
return lo # first index with a[i] >= x, or len(a)When to use and when not to
| Situation | Binary search | Alternative |
|---|---|---|
| Many lookups on static sorted data | Yes, about log n per query | None needed |
| One lookup on unsorted data | No, sorting costs n log n | Linear scan |
| Repeated point lookups, order not needed | Works, slower | Hash set, O(1) expected |
| Predecessor, successor, range | Yes | Hash set needs a full scan |
| Each probe is a remote call | Costs one round trip per probe | One bulk fetch |
| Rows and columns both sorted | No, use the staircase walk | O(rows + cols) |
Hypothetical sizing: 200,000 queries/s, 96% point lookups and 4% ordered. A sorted array at 250 ns per query uses 50 ms of each second. A hash set fails the ordered 4%: 8,000 queries/s at 40 ms each needs 320 s of work per second. Keep the sorted array.
Traps interviewers probe
- Arbitrary match among duplicates. Plain search returns any matching index. Fix: send equality left for the first match and right for the last, using bisect_left and bisect_right. The count is their difference, and it is zero when the value is absent.
- Mixed bound conventions. Setting hi = len(a) - 1 with half-open updates skips or repeats elements. Fix: pick one convention, comment it, and test a target above the largest element, which should return len(a). Tests that only query stored values never reach that case.
- Non-monotone predicate. A hit-rate curve that dips (92%, then 88%) makes the search land on a point that is not the first to qualify. Fix: prove monotonicity before searching. If the predicate flips more than once, binary search does not apply.
- Rotated arrays with duplicates. When a[lo] == a[mid] == a[hi], neither half is known to be sorted, so the search degrades to O(n). Fix: shrink both ends by one element in that case, and state the degraded bound.
- Floating-point termination. Looping while hi - lo > eps can stall when mid rounds to an endpoint and the bounds stop moving. Fix: use a fixed iteration count, or stop when mid is no longer strictly between lo and hi.
Interview tips
Open by naming the predicate and where it flips, then state the invariant: the answer stays inside [lo, hi).
Expect these follow-ups:
- Why half-open? One convention removes the off-by-one cases, and the empty range is exactly lo == hi.
- Minimum of a rotated array: compare mid with hi, not lo, and move hi to mid rather than past it.
- Two orders of magnitude more data: about 7 more probes, since log2(100) is about 6.6.
- Why the high bound of an answer search must be feasible by construction, not by looking large.
30-second outline:
- Name the monotone predicate and the boundary it finds.
- Use a half-open range, and say the loop ends at lo == hi.
- For duplicates, say which direction equality moves the search.
- Give the cost: about log2 n probes, times the cost of one check. Name the degraded case if duplicates can break the structure.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.