Skip to content
Tech Interview Prep
Technical interview guide

Binary Search

Halving the search space on sorted data, and the many variants beyond a plain lookup.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Language-neutral, with library behaviour cited from CPython 3.14 bisect, the C++ standard algorithms, and java.util as of Java 21.

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

probes=⌈log⁡2n⌉\text{probes} = \lceil \log_2 n \rceil

For n = 1,000,000 that is 20; for n = 2^30 it is 30. Doubling the input adds one probe.

Tanswer search=O(log⁡(hi−lo))⋅TcheckT_{\text{answer search}} = O\big(\log(hi - lo)\big) \cdot T_{\text{check}}

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.

Python
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)
yes no yes no Range lo to hi half-open mid = lo + (hi - lo) // 2 pred at mid true hi = mid lo = mid + 1 lo < hi return lo

When to use and when not to

SituationBinary searchAlternative
Many lookups on static sorted dataYes, about log n per queryNone needed
One lookup on unsorted dataNo, sorting costs n log nLinear scan
Repeated point lookups, order not neededWorks, slowerHash set, O(1) expected
Predecessor, successor, rangeYesHash set needs a full scan
Each probe is a remote callCosts one round trip per probeOne bulk fetch
Rows and columns both sortedNo, use the staircase walkO(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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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:

  1. Name the monotone predicate and the boundary it finds.
  2. Use a half-open range, and say the loop ends at lo == hi.
  3. For duplicates, say which direction equality moves the search.
  4. 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.