Binary Search · Lesson
Binary search, explained: the idea, the template and every pattern
Learn binary search from scratch: the one idea, a bug-free template in Java, Python, C++ and JavaScript, and 8 interview patterns with practice problems.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
What binary search does
Binary search finds something in a sorted search space by checking the middle and throwing away the half that cannot hold the answer. Every check halves what is left, so n items need about log₂ n checks: a million items in 20 steps, a billion in 30.
A linear scan looks at every item. Binary search uses the order to skip almost all of them. That is the whole trick, and it is why interviewers reach for it whenever an O(n) solution is "too slow".
The one idea behind every variation
You do not really need a sorted array. You need a monotonic condition: a yes/no check ok(x) that is no, no, no, … yes, yes, yes across the search space. Binary search finds where the answers flip.
A sorted array gives you ok(i) = a[i] >= target. A rotated array, "the first bad version", "the slowest speed that still finishes in time" and "the largest distance that still fits" are the same loop with a different ok. Learn to write ok and every pattern below becomes familiar.
The invariant that keeps it bug-free
Almost every binary search bug is an off-by-one or an infinite loop. Both go away if you decide what lo and hi mean and keep that true on every step:
- Exact search: the answer, if it exists, is in
[lo, hi](both ends included). Loop whilelo <= hiand move tomid + 1ormid - 1. - Boundary search: the answer is in
[lo, hi)or ishiitself. Loop whilelo < hi, sethi = midwhenok(mid), elselo = mid + 1.
Compute mid = lo + (hi - lo) / 2 so lo + hi never overflows, and check that every branch makes the range smaller. If a branch sets lo = mid, round mid up, or a two-element range never shrinks.
What it costs
| Operation | Time | Space |
|---|---|---|
| Find a value in a sorted array | O(log n) | O(1) |
| First or last position (lower / upper bound) | O(log n) | O(1) |
| Search a sorted m × n matrix | O(log(m·n)) or O(m + n) | O(1) |
| Search on the answer, range R, O(n) check | O(n log R) | O(1) |
| Sort first, if the input is not sorted | O(n log n) | depends |
Built into your language
int[] a = {1, 3, 3, 5, 8};
Arrays.binarySearch(a, 5); // 3 (index); a negative value when missing
// floor / ceiling on a sorted set or map
TreeSet<Integer> set = new TreeSet<>(List.of(1, 3, 5, 8));
set.floor(4); // 3: largest value <= 4
set.ceiling(4); // 5: smallest value >= 4
set.higher(5); // 8: smallest value > 5 from bisect import bisect_left, bisect_right, insort
a = [1, 3, 3, 5, 8]
bisect_left(a, 3) # 1: first index with a[i] >= 3
bisect_right(a, 3) # 3: first index with a[i] > 3
bisect_right(a, 3) - bisect_left(a, 3) # 2: how many 3s
insort(a, 4) # insert and keep a sorted vector<int> a = {1, 3, 3, 5, 8};
binary_search(a.begin(), a.end(), 5); // true
lower_bound(a.begin(), a.end(), 3) - a.begin(); // 1: first a[i] >= 3
upper_bound(a.begin(), a.end(), 3) - a.begin(); // 3: first a[i] > 3
set<int> s = {1, 3, 5, 8};
*prev(s.upper_bound(4)); // 3: floor of 4
*s.lower_bound(4); // 5: ceiling of 4 // JavaScript has no built-in binary search: keep this helper
function lowerBound(a, target) { // first index with a[i] >= target
let lo = 0, hi = a.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (a[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
lowerBound([1, 3, 3, 5, 8], 3); // 1 Mistakes everyone makes
- Writing
(lo + hi) / 2in Java or C++ with values near 2³¹: it overflows. Uselo + (hi - lo) / 2. - Mixing
while (lo <= hi)withhi = mid: the loop can run forever whenlo == hi. - Setting
lo = midwithmidrounded down: a range of two never shrinks. Round up instead. - Searching an unsorted array. Sort first, or check that the condition really is monotonic.
- Returning
lowithout checking it: if no element satisfies the condition,lolands one past the end.
The 8 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 Exact search and binary search inside a design Find an exact value in a sorted array, then use the same loop inside data structures that are sorted by time or by running sum. 2 variations · 5 problems
- 2 Lower bound, upper bound, floor and ceiling Find where a value would go: the first element ≥ x (lower bound) or > x (upper bound). Floor, ceiling, first and last position and counts all come from these two. 5 variations · 12 problems
- 3 Binary search on a condition: first true No target value at all: binary search the first index where a yes/no condition becomes true. A bad version, an index-parity break or a downhill slope. 3 variations · 3 problems
- 4 Rotated sorted arrays A sorted array cut and swapped. At every mid, one half is still sorted: find out which, then decide whether the answer can be in it. 3 variations · 5 problems
- 5 Searching a sorted 2D matrix Two shapes. A matrix sorted row after row is one long sorted array: binary search the flattened index. A matrix sorted by row and by column is searched by stepping from a corner. 2 variations · 4 problems
- 6 Binary search over numbers: roots, powers, unbounded ranges The search space is a range of numbers, not an array. Square roots and nth roots: the largest x with x² ≤ n. Plus two cousins: halving the exponent and galloping into an unbounded array. 3 variations · 4 problems
- 7 Binary search on the answer The most important pattern for interviews. You cannot find the answer directly, but you can check a guess. If "k works" means every bigger (or smaller) k also works, binary search the guess. 5 variations · 18 problems
- 8 Binary search on a partition Split two sorted arrays so the left parts hold exactly half the elements and everything on the left is ≤ everything on the right. Binary search where to cut the shorter array. 1 variation · 1 problem