Binary Search
Halve the search space on every step: exact match, first and last position, rotated arrays and binary search on the answer, all in O(log n) checks.
Overview
Binary search checks the middle, throws away the half that cannot hold the answer, and repeats. Picture guessing my number from 1 to 100: say 50, then 25 or 75. A million items take at most 20 checks; a billion take at most 30.
It needs one thing: a monotonic yes/no question, no up to a point and yes after it. On a sorted array the question is "is this element at least the target?"; for shipping packages it is "can we ship everything with capacity c?". Precision is the test: know what left and right mean, why the loop ends, and what comes back when the target is missing.
Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.
How many steps it takes
The rule: after k steps, n / 2^k items remain, so the search takes about log2(n) steps. The worst case is the smallest k with 2^k > n, which is ceil(log2(n + 1)).
- 1,000 — 1,000 — 10
- 1,000,000 — 1,000,000 — 20
- 1,000,000,000 — 1,000,000,000 — 30
Each ×1,000 in size adds about 10 checks.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio