Binary Search
Halve the search space every step: values, boundaries and answers.
Binary search fits in ten lines, yet when Jon Bentley asked professional programmers to write one, ninety percent of them turned out to have bugs in their code. The cure is not cleverness but an invariant: one sentence about lo and hi that stays true on every pass, and from which the code, its correctness proof and its running time all follow.
What you’ll learn
- Write lower-bound and upper-bound searches on a half-open range from an explicit invariant, and prove that they stop after at most probes.
- Derive exact search, first and last occurrences, counts and insertion points from the two bounds, by hand and with
bisectandstd::lower_bound. - Recast a problem as the boundary of a monotone predicate: rotated arrays, peaks, integer square roots and optimal answers.
- Recognize binary search in a problem statement, and avoid its classic bugs: loops that never end, overflow, lost duplicates and the wrong library call.
One probe rules out half
Is in an array of numbers? A linear scan compares with in turn, up to comparisons, because each comparison tells it about one element only.
Sorted data changes the deal. If in a sorted array, then every element at index or before is smaller than too, and candidates vanish with a single comparison. Probing the middle of the remaining range every time halves the search space. That is binary search, and candidates run out after about probes.
A sorted array holds one million values. At most how many probes does binary search need to decide whether is among them?
Show the answer
20
Each probe at least halves the candidates, so the count is . Since , that is probes, against up to a million comparisons for a linear scan. A billion values need only 30.
Lower bound: an invariant you can trust
The most useful single routine is the lower bound: the first index with , or if every element is smaller. It is the boundary of the predicate above, and every other question in this lesson reduces to it. Write it on the half-open range , and decide what and mean before you write a single line.
def lower_bound(a, x):
"""First index i with a[i] >= x, or len(a) if there is none."""
lo, hi = 0, len(a) # the answer lies in [lo, hi]
while lo < hi: # invariant: a[i] < x for i < lo, a[i] >= x for i >= hi
mid = lo + (hi - lo) // 2
if a[mid] < x:
lo = mid + 1 # mid and everything left of it is too small
else:
hi = mid # mid is a candidate: the answer is mid or left of it
return loPython integers never overflow, but writing lo + (hi - lo) // 2 everywhere keeps the habit that C++ and Java need.
Invariant. Every index left of holds a value smaller than , and every index from on holds a value of at least . At the start, and , so both claims are about empty ranges and hold.
Preserved. If , sortedness gives for every , so keeps the left claim. Otherwise , so for every , and keeps the right claim. Both updates are legal because the midpoint lies inside the range:
Terminates. Since , either update shrinks , a nonnegative integer: it is a loop variant. When the loop stops, , and the invariant says exactly that is the first index with :
Fast. A range of candidates becomes one of (left branch) or (right branch), never more than . After probes at most candidates remain, and the loop ends when none do:
Think first Why does the code set hi = mid rather than hi = mid - 1 when ?
Because itself may be the answer: it is the first index with whenever . With hi = mid - 1, the invariant would claim , which no comparison has checked. The rule behind every correct binary search: an update may exclude only indices that a comparison has ruled out.
Exact, lower, upper: three questions, one loop
Replace a[mid] < x by a[mid] <= x and the same loop returns the upper bound: the first index with . The copies of occupy exactly the half-open range between the lower bound and the upper bound , so together the two answer most questions about sorted data:
| Question | From the bounds | Library |
|---|---|---|
| First index with | bisect_left(a, x), std::lower_bound | |
| First index with | bisect_right(a, x), std::upper_bound | |
| Is present? | and | std::binary_search |
| How many copies of ? | std::equal_range returns | |
| Last index with , or with | , or ( means none) | the same calls, minus one |
| How many values lie in ? | bisect_right(a, q) - bisect_left(a, p) |
You will also meet the closed-range style: search starting from , loop while lo <= hi, and move to mid + 1 or mid - 1. It suits exact search, which may return as soon as . Both styles are correct, and mixing them is how bugs are born: pick one, write its invariant as a comment, and make every update keep it.
In the sorted list a = [1, 3, 3, 3, 5, 8], what do bisect_left(a, 3) and bisect_right(a, 4) return?
- 1 and 3
- 3 and 4
- 1 and 4
- 1 and 5
Show the answer
C. 1 and 4
The first 3 sits at index 1, so bisect_left(a, 3) = 1. No element equals 4, and the first element greater than 4 is the 5 at index 4, so bisect_right(a, 4) = 4, which is also where 4 would be inserted.
Any monotone question, not just arrays
Nothing in the lower-bound loop needs an array. It needs a range of integers and a yes/no question that switches once. Written in that general form, it solves problems that do not look like searching at all:
def first_true(lo, hi, ok):
"""Smallest v in [lo, hi) with ok(v), or hi if none.
ok must read False ... False True ... True on [lo, hi)."""
while lo < hi:
mid = lo + (hi - lo) // 2
if ok(mid):
hi = mid
else:
lo = mid + 1
return lo
def isqrt(n): # largest x with x * x <= n
return first_true(0, n + 1, lambda x: x * x > n) - 1
def rotation_point(a): # index of the minimum; a is a rotated sorted list, distinct values
return first_true(0, len(a), lambda i: a[i] <= a[-1])
def peak(a): # an index whose value beats its neighbors; neighbors differ
return first_true(0, len(a) - 1, lambda i: a[i] > a[i + 1])Three classic problems, three one-line predicates. isqrt(10**18) returns after 59 probes. In a rotated sorted list, the values the last one form a suffix that starts at the minimum; once you know where it starts, an ordinary search of the correct part finds any .
The peak finder hides a subtlety. With several peaks, is not monotone, yet the loop still works. It keeps the invariant " or , and or ", and when , that index is a peak.
Binary search needs only a property that holds at one end, fails at the other, and survives halving. Monotonicity is the simplest such property, and the bisection method, which hunts a sign change of a continuous function, is the same idea on the real line.
Recognizing it
Reach for binary search when a problem shows one of these signals:
- Sorted data, or data you can sort once and then query many times: "how many values are below ?", "which stored value is nearest to ?".
- A yes/no question that flips once as a number grows: "is capacity enough?", "is the fault already present on day ?".
- Phrases such as the least such that, the first time when, minimize the maximum, maximize the minimum.
- Constraints where the answer can reach or , far too many values to try one by one, while checking one candidate costs . Then fits easily: as a rule of thumb, and 60 checks make simple steps, well under a second.
| Problem, in brief | Key idea | Cost |
|---|---|---|
| The first build, in a history of , that fails a test, when every later build fails too | first_true over build numbers; each check runs the test once | test runs |
| Count the stored values in , or find the stored value nearest to | the two bounds; the nearest value sits at the lower bound or just before it | per query, after an sort |
| Find in a sorted array rotated at an unknown index (distinct values) | find the rotation point with , then search the part that can hold | |
| Find any peak in an array whose neighbors differ | step toward the larger neighbor of | |
| The least daily capacity that ships packages, in order, within days | binary search on the capacity; one greedy pass checks a candidate |
Common bugs.
- A loop that never ends. With
while lo < hi, the updatelo = midstalls once , because the midpoint rounds down to . Round up withmid = lo + (hi - lo + 1) // 2, or keep always true and always false and loopwhile hi - lo > 1. - Overflow.
(lo + hi) / 2overflows 32-bit integers once ; writelo + (hi - lo) / 2. In C++,/rounds toward zero, so with negative bounds(lo + hi) / 2can round up (for , it gives ), whilelo + (hi - lo) / 2always rounds down. - Off-by-one bounds.
hi = nbelongs to the half-open style andhi = n - 1to the closed one. A lower bound equal to means "not found": test for it before readinga[result]. - Duplicates. Exact search returns some copy of ; use the lower bound when you need the first.
- The wrong library call.
std::lower_bound(s.begin(), s.end(), x)on astd::setorstd::maptakes time, because their iterators advance one step at a time. The member functions.lower_bound(x)takes .
#include <algorithm>
#include <cstdio>
#include <set>
#include <vector>
int main() {
std::vector<int> a = {1, 3, 3, 3, 5, 8};
auto lo = std::lower_bound(a.begin(), a.end(), 3); // first element >= 3
auto hi = std::upper_bound(a.begin(), a.end(), 3); // first element > 3
std::printf("%td %td %td\n", lo - a.begin(), hi - a.begin(), hi - lo); // 1 4 3
auto [l, r] = std::equal_range(a.begin(), a.end(), 4); // no 4: an empty range
std::printf("%td %td\n", l - a.begin(), r - a.begin()); // 4 4
// the first element for which the predicate is false (true ... true false ... false)
auto p = std::partition_point(a.begin(), a.end(), [](int v) { return v * v < 20; });
std::printf("%td\n", p - a.begin()); // 4
std::set<int> s(a.begin(), a.end());
std::printf("%d\n", *s.lower_bound(4)); // 5, in O(log n): the member function
}C++17; the comments show the output. std::partition_point (C++11) is first_true for any predicate that reads true…true false…false.
You get positive task durations in a fixed order and must cut them into consecutive blocks, one per worker, so that the busiest worker's total is as small as possible. Which approach fits?
- Binary search on the largest block total, checking each candidate with one greedy pass
- Sort the durations, then deal them out greedily
- A sliding window of fixed length
- Try every way to place the cuts
Show the answer
A. Binary search on the largest block total, checking each candidate with one greedy pass
If a limit allows a split into at most blocks, so does every larger limit, so "does suffice?" is monotone. A greedy pass that opens a new block only when the next task would push the total past decides it in , and about probes find the least : in all.
Key takeaways
- Binary search finds the boundary of a monotone predicate (false…false true…true) in at most probes: 20 for a million candidates, 30 for a billion.
- Write it from an invariant on a half-open range: everything left of is false, everything from on is true. Each update must keep that sentence true and shrink .
- The lower bound (first ) and the upper bound (first ) answer presence, counts, ranges and nearest values; in libraries they are
bisect_left/bisect_rightandstd::lower_bound/std::upper_bound. - Many problems hide a monotone question: rotated arrays, peaks, integer roots, and "the least capacity that works", which is binary search on the answer.
- The classic bugs: a loop that stalls on
lo = mid, midpoint overflow, returning an arbitrary copy of a duplicate, and callingstd::lower_boundon astd::set.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A sorted array has exactly elements. What is the largest number of probes the lower-bound loop can make on it?
- 20
- 21
- 10
Show the answer
B. 21
The count is . Twenty halvings can leave one candidate, and settling it takes one more probe. For the bound drops to 20.
A loop keeps lo on a value where ok holds and runs while lo < hi: it computes mid = (lo + hi) // 2, then sets lo = mid if ok(mid), else hi = mid - 1. With ok(v) = v * v <= 30, lo = 0 and hi = 10, what happens?
- It returns 5
- It returns 6
- It never stops: once
hi = lo + 1andok(lo)holds,midequalsloand nothing changes - It raises an index error
Show the answer
C. It never stops: once hi = lo + 1 and ok(lo) holds, mid equals lo and nothing changes
The search reaches , . Then , ok(5) holds since , and lo = mid leaves the state unchanged forever. Rounding the midpoint up, mid = lo + (hi - lo + 1) // 2, makes every update shrink the range, and the loop returns 5.
In a sorted Python list a, which expression counts the values with ?
bisect_left(a, q) - bisect_left(a, p)bisect_right(a, q) - bisect_right(a, p)bisect_right(a, q) - bisect_left(a, p)bisect_right(a, q) - bisect_left(a, p) + 1
Show the answer
C. bisect_right(a, q) - bisect_left(a, p)
bisect_left(a, p) is the first index with and bisect_right(a, q) the first with , so the values in occupy exactly the indices from the first up to, but not including, the second.
Searching a rotated sorted array of distinct values takes time. Why can the same task need time when values may repeat?
- Duplicates make it impossible to rotate the array back
- When , no comparison tells which half holds the rotation point, so it can hide anywhere
- Binary search needs distinct values to compute
mid - Python's
bisectrejects lists with duplicates
Show the answer
B. When , no comparison tells which half holds the rotation point, so it can hide anywhere
In and in , the probes at , and all see 1. Until some probe hits the lone 0, every answer looks the same, so an algorithm may have to inspect nearly every position. Standard solutions shrink the range by one in this case, which is correct but linear in the worst case.
For which question is the yes/no answer guaranteed to be monotone in the integer , so that binary search over is safe?
- "Is there a subarray of exactly elements with sum at most ?", when values may be negative
- "Is ?", in an array that rises and falls several times
- "Is day the hottest day of the month?"
- "Can the jobs, kept in their given order, be split among workers so that nobody works more than hours?"
Show the answer
D. "Can the jobs, kept in their given order, be split among workers so that nobody works more than hours?"
A split that respects a limit also respects every larger limit, so the answers read no…no yes…yes, and binary search finds the least feasible . The other three questions can switch back and forth.
Go deeper
- Binary Search on the Answer · Turn “minimize the maximum” into a yes-or-no question and search over answers.
- Exponential & Interpolation Search · Searching unbounded lists and uniform data, plus fractional cascading across many lists.
- Ternary Search & Continuous Bisection · Unimodal functions, golden-section search and searching over real numbers.
Further reading
- J. Bentley, Programming Pearls, 2nd ed. (Addison-Wesley, 2000), column 4, "Writing Correct Programs".
- D. E. Knuth, The Art of Computer Programming, Vol. 3: Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), §6.2.1.
- J. Bloch, "Extra, Extra – Read All About It: Nearly All Binary Searches and Mergesorts are Broken," Google Research Blog (2006).
- A. Laaksonen, Guide to Competitive Programming, 2nd ed. (Springer, 2020), the sections on binary search.