Binary Search
Binary search finds a target value in a sorted array by repeatedly halving the search range: probe the middle element, discard the half that cannot contain the target, and repeat. Its time complexity is O(log n), settling a million-element array in at most twenty comparisons.
It works like a number-guessing game from 1 to 100: guessing 50 and hearing "higher" eliminates half the range without checking each value. Binary search requires the array to be sorted so that comparing against nums[mid] (for instance, seeing 16 < 23) rules out every element on the discarded side.
How Binary Search Works
Maintain a window [lo, hi] over the slice that can still contain the target, initialized to lo = 0 and hi = n − 1 (inclusive on both ends). Each iteration performs three steps:
- Compute the midpoint,
mid = (lo + hi) // 2. - Compare
nums[mid]withtarget. - Update the window. Equal → return
mid.nums[mid] < target→ the target, if present, lies to the right, solo = mid + 1.nums[mid] > target→hi = mid − 1.
Excluding mid with +1 or −1 guarantees that the window shrinks every iteration, because mid has already been checked and rejected. The loop invariant proves correctness: if the target exists in the array, it lies in nums[lo..hi]. When lo > hi, the window is empty while the invariant still holds, so the target is absent and the function returns −1.
Binary Search Step by Step
The default input is nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] with target = 23.
lo = 0,hi = 9→mid = 4.nums[4] = 16, and16 < 23, so the target lies to the right. Discard indices 0–4 and setlo = 5, eliminating half the array in one comparison.lo = 5,hi = 9→mid = 7.nums[7] = 56 > 23, which is too high. Discard indices 7–9 and sethi = 6.lo = 5,hi = 6→mid = 5.nums[5] = 23, matching the target. Return index 5.
Ten elements take three probes. If the target were absent (say 24), the window would continue shrinking until lo crossed hi, returning −1.
On the canvas, the left and right walls of [lo, hi] move inward while the mid pointer drops onto the center of the remaining slice. Every cell outside [lo, hi] fades out once ruled out, showing half of the remaining candidates eliminated after each comparison. The matched cell turns green.
Time and Space Complexity
| Case | Time |
|---|---|
Best (target at the first mid) | O(1) |
| Average | O(log n) |
| Worst (target absent or at an extreme) | O(log n) |
Space is O(1): the iterative form uses two integer pointers and no recursion stack. Because each step halves the remaining range, at most twenty comparisons settle a million elements and thirty settle a billion; doubling the input adds one comparison.
Edge Cases
- Empty array:
hi = −1, solo <= hifails on entry and returns −1 with zero probes. - Single element:
lo = hi = 0; one comparison decides the result. - Target at the first or last index: the window shrinks toward that end over ~log n rounds before matching, making the extremes the worst case rather than the best.
- Target between two adjacent elements: the window collapses to one cell, that cell fails the comparison, the bounds cross, and the function returns −1.
- Duplicates: vanilla binary search returns the index of some matching element, which may be any occurrence rather than the first or last; finding the first or last requires the
bisect_left/bisect_rightvariant.
Common Mistakes
lo = midinstead oflo = mid + 1. Whenloandhiare adjacent,midrounds down tolo, the update changes nothing, and the loop spins forever. The player includes this bug as a mode: switch the variant tolo = midand the window narrows to two cells, freezes there, and never returns.lo < hiinstead oflo <= hi. The bounds are inclusive, so<abandons single-cell windows one iteration early and misses targets sitting in them. Switch the variant tolo < hiand search for the smallest element: the window collapses onto the right cell, the loop exits without checking it, and a present value comes back as "not found."- Midpoint overflow. In Java or C++,
lo + hican overflow a 32-bit int; writelo + (hi - lo) / 2. Python's integers are arbitrary-precision, so the displayed code is safe as written. - Running it on unsorted data. A probe can discard the half holding the target, causing the search to return
-1for a present value. Any index it does return still points to a real match because every hit is checked with==, but sortedness is the precondition that makes discarding a half valid. - Using it where a hash set wins. Membership-only queries take O(1) average time with a set. Binary search is preferable when you need position (such as an insertion point or nearest neighbor), which hashing cannot provide.
Keep exploring
A few lessons that share the same technique or lead into the next idea.
Embed this lesson in a blog, docs, or course?
Found a mistake or something unclear?