synopsis · Linear patterns · chapter 18
Binary Search
8 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
Look at the middle and throw away the half that can't hold the answer. n → n/2 → … → 1 takes about log₂ n looks: 20 for a million.
- use it when
Sorted data, or any yes/no test that flips once (
F F F T T T): first/last position, rotated arrays, peaks, "minimum speed that works". - template
Exact:
hi = n − 1,while (lo <= hi), movemid ± 1. Boundary:hi = n,while (lo < hi),hi = midorlo = mid + 1, return lo. - cost
O(log n) time, O(1) space (iterative). On the answer: O(check × log range) — about 30 checks for a range of 10⁹.
- trap
(lo + hi) / 2overflows past 2³¹ − 1. Writelo + (hi − lo) / 2— the JDK itself carried this bug for about nine years. - trap
lo = midwith a rounded-down mid loops forever when hi = lo + 1. Uselo = mid + 1, or round mid up. - trap
Arrays.binarySearchreturns-(insertion point) − 1when missing, and any copy among duplicates. Need first/last? Use lower/upper bound. - pro tip
Say the invariant out loud — "the answer is always in [lo, hi]" — and dry-run a 2-element array before you trust the loop.
Shaky on a card? Open the chapter or flip its recall cards.