Binary search: find anything in a sorted array in 30 steps
Halve the search space on every step. The classic version, the off-by-one traps, and the variant interviewers love: binary search on the answer.
In short
If the data is sorted (or the answer is monotonic), look at the middle and throw away the half that can't contain the answer. Each step halves the problem: O(log n).
The idea: open the dictionary in the middle
Looking for a word in a paper dictionary, nobody reads from page 1. You open it around the middle, see you went too far, and keep only the half where the word must be. Then you repeat.
That only works because the dictionary is sorted. With sorted data, one comparison tells you which half to discard, so the number of candidates goes 1,000,000 → 500,000 → 250,000… and reaches one in about 20 steps.
Watch it run
Step through it, change the target, or type your own sorted array. Watch the range between lo and hi shrink by half on every comparison. The code panel follows along in Python, TypeScript or Java.
1def binary_search(nums, target):2 lo, hi = 0, len(nums) - 13 while lo <= hi:4 mid = lo + (hi - lo) // 25 if nums[mid] == target:6 return mid7 if nums[mid] < target:8 lo = mid + 19 else:10 hi = mid - 111 return -1
Variables
The three classic traps
- `lo <= hi`, not `lo < hi` (in this version). With
<, a one-element range is never checked and you miss the answer when it's the last candidate. - `lo = mid + 1` and `hi = mid - 1`. If you write
lo = mid, a two-element range can loop forever, becausemidkeeps landing onlo. - `mid = lo + (hi - lo) / 2`.
(lo + hi) / 2overflows a 32-bit integer on huge arrays. This exact bug sat in Java's standard library for about nine years until it was found in 2006.
Variants that show up in interviews
| Problem shape | What changes | Example |
|---|---|---|
| First / last occurrence | On a match, keep searching left (or right) instead of returning | First and last position of a value in a sorted array |
| Insert position (lower bound) | Find the first index where nums[i] >= target | Where would this value go to keep the array sorted? |
| Rotated sorted array | One half is always sorted: check which, then whether the target is in it | Search in an array rotated at an unknown pivot |
| Binary search on the answer | Search over possible answers, with a yes/no check that is monotonic | Minimum ship capacity to deliver all packages in D days |
The last one is the big unlock. If you can write canDo(x) and it's false, false, false… then true, true, true as x grows, you can binary search for the first true, even though there is no array at all.
How to recognise it
- The input is sorted, or the problem says "in O(log n)".
- You're asked for the minimum or maximum value that satisfies a condition.
- A brute force tries every value from 1 to a huge number one by one.
- The condition flips only once as the value grows (monotonic).
Key takeaways
- 01Binary search halves the candidates each step: O(log n) time, O(1) space.
- 02It needs sorted data or a monotonic yes/no condition.
- 03Keep the invariant "the answer is in [lo, hi]" and update with mid ± 1.
- 04Binary search on the answer solves many "minimum value such that…" problems.
Check your understanding
1 of 3
What does binary search need from the data?
Related topics