Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

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 ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 probes.
  • Derive exact search, first and last occurrences, counts and insertion points from the two bounds, by hand and with bisect and std::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 xx in an array of nn numbers? A linear scan compares xx with a[0],a[1],…a[0], a[1], \dots in turn, up to nn comparisons, because each comparison tells it about one element only.

Sorted data changes the deal. If a[m]<xa[m] < x in a sorted array, then every element at index mm or before is smaller than xx too, and m+1m + 1 candidates vanish with a single comparison. Probing the middle of the remaining range every time halves the search space. That is binary search, and nn candidates run out after about log⁡2n\log_2 n probes.

Predict before you look

A sorted array holds one million values. At most how many probes does binary search need to decide whether xx is among them?

Show the answer

20

Each probe at least halves the candidates, so the count is ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1. Since 219=524,288≤106<2202^{19} = 524{,}288 \le 10^6 < 2^{20}, that is 19+1=2019 + 1 = 20 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 ii with a[i]≥xa[i] \ge x, or nn 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 [lo,hi)[lo, hi), and decide what lolo and hihi mean before you write a single line.

python
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 lo

Python integers never overflow, but writing lo + (hi - lo) // 2 everywhere keeps the habit that C++ and Java need.

DerivationCorrectness, termination and the probe count
  1. a[i]<x  for i<lo,a[i]≥x  for i≥hia[i] < x \ \text{ for } i < lo, \qquad a[i] \ge x \ \text{ for } i \ge hi

    Invariant. Every index left of lolo holds a value smaller than xx, and every index from hihi on holds a value of at least xx. At the start, lo=0lo = 0 and hi=nhi = n, so both claims are about empty ranges and hold.

  2. lo  ≤  mid=lo+⌊hi−lo2⌋  <  hilo \;\le\; mid = lo + \left\lfloor \tfrac{hi - lo}{2} \right\rfloor \;<\; hi

    Preserved. If a[mid]<xa[mid] < x, sortedness gives a[i]<xa[i] < x for every i≤midi \le mid, so lo=mid+1lo = mid + 1 keeps the left claim. Otherwise a[mid]≥xa[mid] \ge x, so a[i]≥xa[i] \ge x for every i≥midi \ge mid, and hi=midhi = mid keeps the right claim. Both updates are legal because the midpoint lies inside the range:

  3. lo=hi=min⁡{ i:a[i]≥x }(or n if there is none)lo = hi = \min\{\, i : a[i] \ge x \,\} \quad (\text{or } n \text{ if there is none})

    Terminates. Since lo≤mid<hilo \le mid < hi, either update shrinks hi−lohi - lo, a nonnegative integer: it is a loop variant. When the loop stops, lo=hilo = hi, and the invariant says exactly that lolo is the first index with a[i]≥xa[i] \ge x:

  4. probes  ≤  ⌊log⁡2n⌋+1  =  ⌈log⁡2(n+1)⌉\text{probes} \;\le\; \lfloor \log_2 n \rfloor + 1 \;=\; \lceil \log_2 (n + 1) \rceil

    Fast. A range of ss candidates becomes one of ⌊s/2⌋\lfloor s/2 \rfloor (left branch) or ⌈s/2⌉−1\lceil s/2 \rceil - 1 (right branch), never more than ⌊s/2⌋\lfloor s/2 \rfloor. After tt probes at most ⌊n/2t⌋\lfloor n/2^t \rfloor candidates remain, and the loop ends when none do:

Think first Why does the code set hi = mid rather than hi = mid - 1 when a[mid]≥xa[mid] \ge x?

Because midmid itself may be the answer: it is the first index with a[i]≥xa[i] \ge x whenever a[mid−1]<xa[mid - 1] < x. With hi = mid - 1, the invariant would claim a[mid−1]≥xa[mid - 1] \ge x, 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 a[i]>xa[i] > x. The copies of xx occupy exactly the half-open range [L,U)[L, U) between the lower bound LL and the upper bound UU, so together the two answer most questions about sorted data:

QuestionFrom the boundsLibrary
First index with a[i]≥xa[i] \ge xLLbisect_left(a, x), std::lower_bound
First index with a[i]>xa[i] > xUUbisect_right(a, x), std::upper_bound
Is xx present?L<nL < n and a[L]=xa[L] = xstd::binary_search
How many copies of xx?U−LU - Lstd::equal_range returns [L,U)[L, U)
Last index with a[i]≤xa[i] \le x, or with a[i]<xa[i] < xU−1U - 1, or L−1L - 1 (−1-1 means none)the same calls, minus one
How many values lie in [p,q][p, q]?U(q)−L(p)U(q) - L(p)bisect_right(a, q) - bisect_left(a, p)
Here nn is the length of the array; every row costs one or two searches, O(log⁡n)O(\log n) time.

You will also meet the closed-range style: search [lo,hi][lo, hi] starting from hi=n−1hi = n - 1, loop while lo <= hi, and move to mid + 1 or mid - 1. It suits exact search, which may return as soon as a[mid]=xa[mid] = x. 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.

Check your understanding

In the sorted list a = [1, 3, 3, 3, 5, 8], what do bisect_left(a, 3) and bisect_right(a, 4) return?

  1. 1 and 3
  2. 3 and 4
  3. 1 and 4
  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:

python
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 10910^9 after 59 probes. In a rotated sorted list, the values ≤\le 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 xx.

The peak finder hides a subtlety. With several peaks, a[i]>a[i+1]a[i] > a[i+1] is not monotone, yet the loop still works. It keeps the invariant "a[lo−1]<a[lo]a[lo - 1] < a[lo] or lo=0lo = 0, and a[hi]>a[hi+1]a[hi] > a[hi + 1] or hi=n−1hi = n - 1", and when lo=hilo = hi, 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 xx?", "which stored value is nearest to xx?".
  • A yes/no question that flips once as a number grows: "is capacity cc enough?", "is the fault already present on day dd?".
  • Phrases such as the least xx such that, the first time when, minimize the maximum, maximize the minimum.
  • Constraints where the answer can reach 10910^9 or 101810^{18}, far too many values to try one by one, while checking one candidate costs O(n)O(n). Then O(nlog⁡(range))O(n \log(\text{range})) fits easily: as a rule of thumb, n=105n = 10^5 and 60 checks make 6×1066 \times 10^6 simple steps, well under a second.
Problem, in briefKey ideaCost
The first build, in a history of nn, that fails a test, when every later build fails toofirst_true over build numbers; each check runs the test onceO(log⁡n)O(\log n) test runs
Count the stored values in [p,q][p, q], or find the stored value nearest to xxthe two bounds; the nearest value sits at the lower bound or just before itO(log⁡n)O(\log n) per query, after an O(nlog⁡n)O(n \log n) sort
Find xx in a sorted array rotated at an unknown index (distinct values)find the rotation point with a[i]≤a[n−1]a[i] \le a[n-1], then search the part that can hold xxO(log⁡n)O(\log n)
Find any peak in an array whose neighbors differstep toward the larger neighbor of midmidO(log⁡n)O(\log n)
The least daily capacity that ships nn packages, in order, within DD daysbinary search on the capacity; one greedy pass checks a candidateO(nlog⁡∑w)O(n \log \sum w)
Each row is a predicate that switches once (for peaks, a switch that is guaranteed to exist) plus the same lower-bound loop.

Common bugs.

  • A loop that never ends. With while lo < hi, the update lo = mid stalls once hi=lo+1hi = lo + 1, because the midpoint rounds down to lolo. Round up with mid = lo + (hi - lo + 1) // 2, or keep lolo always true and hihi always false and loop while hi - lo > 1.
  • Overflow. (lo + hi) / 2 overflows 32-bit integers once lo+hi>231−1lo + hi > 2^{31} - 1; write lo + (hi - lo) / 2. In C++, / rounds toward zero, so with negative bounds (lo + hi) / 2 can round up (for lo=−3lo = -3, hi=−2hi = -2 it gives −2-2), while lo + (hi - lo) / 2 always rounds down.
  • Off-by-one bounds. hi = n belongs to the half-open style and hi = n - 1 to the closed one. A lower bound equal to nn means "not found": test for it before reading a[result].
  • Duplicates. Exact search returns some copy of xx; use the lower bound when you need the first.
  • The wrong library call. std::lower_bound(s.begin(), s.end(), x) on a std::set or std::map takes O(n)O(n) time, because their iterators advance one step at a time. The member function s.lower_bound(x) takes O(log⁡n)O(\log n).
cpp
#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.

Check your understanding

You get n≤105n \le 10^5 positive task durations in a fixed order and must cut them into kk consecutive blocks, one per worker, so that the busiest worker's total is as small as possible. Which approach fits?

  1. Binary search on the largest block total, checking each candidate with one greedy pass
  2. Sort the durations, then deal them out greedily
  3. A sliding window of fixed length n/kn/k
  4. Try every way to place the k−1k - 1 cuts
Show the answer

A. Binary search on the largest block total, checking each candidate with one greedy pass

If a limit TT allows a split into at most kk blocks, so does every larger limit, so "does TT suffice?" is monotone. A greedy pass that opens a new block only when the next task would push the total past TT decides it in O(n)O(n), and about log⁡2∑di\log_2 \sum d_i probes find the least TT: O(nlog⁡∑di)O(n \log \sum d_i) in all.

Key takeaways

  • Binary search finds the boundary of a monotone predicate (false…false true…true) in at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 probes: 20 for a million candidates, 30 for a billion.
  • Write it from an invariant on a half-open range: everything left of lolo is false, everything from hihi on is true. Each update must keep that sentence true and shrink hi−lohi - lo.
  • The lower bound (first a[i]≥xa[i] \ge x) and the upper bound (first a[i]>xa[i] > x) answer presence, counts, ranges and nearest values; in libraries they are bisect_left/bisect_right and std::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 calling std::lower_bound on a std::set.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A sorted array has exactly 220=1,048,5762^{20} = 1{,}048{,}576 elements. What is the largest number of probes the lower-bound loop can make on it?

  1. 20
  2. 21
  3. 2192^{19}
  4. 10
Show the answer

B. 21

The count is ⌊log⁡2n⌋+1=20+1=21\lfloor \log_2 n \rfloor + 1 = 20 + 1 = 21. Twenty halvings can leave one candidate, and settling it takes one more probe. For n=220−1n = 2^{20} - 1 the bound drops to 20.

Question 2

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?

  1. It returns 5
  2. It returns 6
  3. It never stops: once hi = lo + 1 and ok(lo) holds, mid equals lo and nothing changes
  4. 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 lo=5lo = 5, hi=6hi = 6. Then mid=5mid = 5, ok(5) holds since 25≤3025 \le 30, 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.

Question 3

In a sorted Python list a, which expression counts the values vv with p≤v≤qp \le v \le q?

  1. bisect_left(a, q) - bisect_left(a, p)
  2. bisect_right(a, q) - bisect_right(a, p)
  3. bisect_right(a, q) - bisect_left(a, p)
  4. 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 a[i]≥pa[i] \ge p and bisect_right(a, q) the first with a[i]>qa[i] > q, so the values in [p,q][p, q] occupy exactly the indices from the first up to, but not including, the second.

Question 4

Searching a rotated sorted array of distinct values takes O(log⁡n)O(\log n) time. Why can the same task need Θ(n)\Theta(n) time when values may repeat?

  1. Duplicates make it impossible to rotate the array back
  2. When a[lo]=a[mid]=a[hi]a[lo] = a[mid] = a[hi], no comparison tells which half holds the rotation point, so it can hide anywhere
  3. Binary search needs distinct values to compute mid
  4. Python's bisect rejects lists with duplicates
Show the answer

B. When a[lo]=a[mid]=a[hi]a[lo] = a[mid] = a[hi], no comparison tells which half holds the rotation point, so it can hide anywhere

In [1,1,1,1,0,1,1][1, 1, 1, 1, 0, 1, 1] and in [1,1,0,1,1,1,1][1, 1, 0, 1, 1, 1, 1], the probes at lolo, midmid and hihi 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.

Question 5

For which question is the yes/no answer guaranteed to be monotone in the integer vv, so that binary search over vv is safe?

  1. "Is there a subarray of exactly vv elements with sum at most SS?", when values may be negative
  2. "Is a[v]>a[v+1]a[v] > a[v+1]?", in an array that rises and falls several times
  3. "Is day vv the hottest day of the month?"
  4. "Can the jobs, kept in their given order, be split among kk workers so that nobody works more than vv hours?"
Show the answer

D. "Can the jobs, kept in their given order, be split among kk workers so that nobody works more than vv hours?"

A split that respects a limit vv also respects every larger limit, so the answers read no…no yes…yes, and binary search finds the least feasible vv. The other three questions can switch back and forth.

Go deeper

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.