Binary Search — halve it until it’s found
The logarithmic idea behind sorted-array lookups, bisect, database indexes and git bisect: loop invariants, lower and upper bounds, the off-by-one traps, the 50-year-old overflow bug, and binary search on the answer.
AChapter introduction
Prerequisites
You should be comfortable with Python lists, loops, functions and integer division (//), and with Big-O notation. Two earlier chapters help directly: Chapter 01 · Time & Space Complexity (logarithms, recurrences, the linear-vs-binary race) and Chapter 02 · Arrays & Hashing (why a[i] costs O(1)). Recursion is used once, in a short alternative implementation.
Learning objectives
After completing this chapter you will be able to:
- Explain why binary search needs sorted data and random access, and why it makes at most ⌊log₂ n⌋ + 1 comparisons.
- Write a correct binary search from memory by stating its loop invariant first, and prove it terminates.
- Choose between the closed-interval
[lo, hi]and half-open[lo, hi)templates and avoid the classic off-by-one and infinite-loop bugs. - Use lower bound and upper bound (Python’s
bisect_left/bisect_right) to find first/last occurrences, counts, insertion points and predecessors. - Recognise “binary search on the answer”: turn an optimisation problem into a monotone yes/no predicate and search over the answer space.
- Prove the Ω(log n) lower bound for comparison-based search with a decision tree, and know when other methods (hashing, interpolation, Eytzinger layout) beat plain binary search.
BFundamental understanding
What is binary search?
Binary search finds a value in a sorted sequence by repeatedly comparing it with the element in the middle of the part that could still contain it, and throwing away the half that cannot. Princeton’s Algorithms text presents it as the reason to keep symbol-table keys in an ordered array: array indexing lets us jump to the middle, which “dramatically” reduces the number of comparisons. [3] CP-Algorithms describes the same idea more generally as “splitting the search interval into two” — the target need not even be an array element, as Section N shows. [5]
Why does it exist, and what came before it?
Before binary search, the only general way to look something up was linear (sequential) search: check items one by one, which costs O(n) comparisons — Python’s x in my_list is exactly such a scan. [22] Sorting the data first buys a powerful guarantee: every element to the left of position m is ≤ A[m] and every element to the right is ≥ A[m]. One comparison therefore tells you about half the array at once. Binary search exists to cash in on that guarantee. MIT 6.006 shows that in the comparison model no algorithm can do better than Ω(log n) for searching, so binary search is optimal there. [1][2]
A little history
Ordered tables for lookup are ancient: Knuth’s history of searching (as summarised in the Wikipedia survey) cites a Babylonian tablet from about 200 BCE holding a sorted table. [9][10] The first explicit description of binary search for computers is credited to John Mauchly in the 1946 Moore School Lectures. [9] Getting it right took longer: Jon Bentley wrote that although the first binary search was published in 1946, the first version correct for all values of n did not appear until 1962. [8] Bentley also reported that when he assigned binary search to professional programmers, about ninety percent failed to produce a correct solution. [9] And in 2006 Joshua Bloch showed that the textbook midpoint line mid = (low + high) / 2 — including the one in Java’s own library, which he had written — overflows on arrays of about 230 elements. [8] The idea is simple; the details are where people slip, which is why this chapter spends so long on invariants.
Fundamental principles
- Order lets one comparison speak for many elements. If A[m] < x and the array is sorted, then every A[i] with i ≤ m is also < x. [3]
- Random access makes the middle cheap. Jumping to index m must be O(1), as in an array; on a linked list, reaching the middle costs O(n) and the advantage disappears. [22]
- Halving gives logarithms. An interval of size n can be halved only about log₂ n times before it is empty. [5]
- An invariant keeps you honest. State what the interval means (“if x is present, it is inside [lo, hi]”) and make every update preserve that statement. Correctness and termination follow. [5]
- Really, you are finding a boundary. Most binary-search problems ask for the first position where a yes/no question flips from “no” to “yes”. That view — a monotone predicate — is what makes binary search a general technique. [11][5]
Terminology used in this chapter
| Term | Meaning |
|---|---|
| Search interval | The indices that might still hold the answer, written [lo, hi] (both ends included) or [lo, hi) (hi excluded). |
| Probe / mid | The index compared in this step, normally (lo + hi) // 2. |
| Invariant | A statement about lo, hi that is true before and after every loop iteration. |
| Lower bound | The first index i with A[i] ≥ x (= bisect_left). Also the insertion point and the rank of x: the number of elements smaller than x. [6][3] |
| Upper bound | The first index i with A[i] > x (= bisect_right). [6][20] |
| Monotone predicate | A yes/no function p over an ordered space that is False…False then True…True. Binary search finds the first True. [11] |
CThe problem statement
The sorted search problem
| Component | Specification |
|---|---|
| Input | A sequence A of n comparable keys, sorted in non-decreasing order, supporting O(1) access by index; and a query key x. |
| Output | An index i with A[i] = x, or a signal that x is absent (−1). Useful variants return the insertion point, the first or last occurrence, or the count of x. |
| Constraints | Many queries against the same data; n may be millions or billions; we want far fewer than n comparisons per query. |
| Model | Keys are only compared with each other (<, =, >) — the comparison model, in which the cost is the number of comparisons. [1] |
Why the naive approach is inefficient
Linear search ignores the order and may look at every element: n comparisons in the worst case and about n/2 on average for a successful search. For a table of 109 keys answering 105 queries, that is up to 1014 comparisons. Binary search answers the same workload with at most 30 × 105 = 3·106. [3][5]
Limitations of alternative approaches
A hash table answers “is x present?” in expected O(1), but it keeps no order, so it cannot answer “what is the largest key ≤ x?” or “how many keys lie between 10 and 20?”. MIT 6.006’s data-structure table records exactly this: hash tables have no efficient find_next, while a sorted array supports it in O(log n). [2] The Python documentation itself notes that bisection is the right tool for range searches and dictionaries for exact lookups. [6] A balanced binary search tree supports ordered queries and fast insertion, but uses extra pointers per key and has poorer memory locality than a flat array.
How binary search improves the solution
It exploits the order that is already there. Each comparison halves the candidates, so the work grows with log n, not n, and the only extra memory is two or three integer indices. The price is paid up front: the data must be sorted (O(n log n) once) and kept sorted, and inserting into a sorted array costs O(n) because elements shift. [2][3][6]
DVisual whiteboard explanations
All diagrams in this chapter use one colour language:
mid, the element being compared
Purple — pointers, relationships, recursion
Black — labels and definitions
- Secret number 37, range 1–100. Guess the middle, 50: “too high” → everything from 50 to 100 is crossed out.
- Range 1–49, guess 25: “too low” → 1 to 25 crossed out.
- Range 26–49, guess the middle, 37: found in 3 guesses. No secret in 1–100 needs more than 7, because 27 = 128 ≥ 100.
- Top: a sorted array of 10 integers stored contiguously from (illustrative) base address 2000, 8 bytes per slot.
- The middle index is
(0 + 9) // 2 = 4, and its address is computed directly:2000 + 4 × 8 = 2032. One step. - Bottom: the same keys in a linked list. To reach the 5th node you must follow 4
nextpointers; every probe of a binary search would cost a walk.
a[i]; linked structures do not. [22][3]
- Step 1: lo = 0, hi = 9, mid = 4, A[4] = 16 < 23 → the answer must be right of 4:
lo = 5. - Step 2: lo = 5, hi = 9, mid = 7, A[7] = 56 > 23 → answer left of 7:
hi = 6. - Step 3: lo = 5, hi = 6, mid = 5, A[5] = 23 = target → return 5. Three comparisons for ten elements.
- Searching for 40 probes indices 4 (16), 7 (56), 5 (23) and 6 (38).
- After the last probe
lo = 7andhi = 6: the interval[7, 6]is empty, so 40 is absent. - Bonus:
lo = 7is exactly where 40 would have to be inserted to keep the array sorted — between 38 and 56.
bisect_left returns. [6][3]
- Array
[1, 2, 2, 2, 3, 5, 8], key 2. Ask “is A[i] ≥ 2?” at every index: F T T T T T T. The first True is index 1 → lower bound. - Ask “is A[i] > 2?”: F F F F T T T. The first True is index 4 → upper bound.
- The copies of 2 occupy
[1, 4), so the count is 4 − 1 = 3.
< or ≤. Python names them bisect_left and bisect_right; C++ names them lower_bound and upper_bound. [6][20][5]
- Start with n = 1 000 000 candidates. After each comparison at most ⌊size/2⌋ remain (the half on one side of mid).
- Sizes: 1 000 000 → 500 000 → 250 000 → … → 1 after 19 halvings; the 20th comparison checks the last candidate.
- Linear search may need all 1 000 000 comparisons for the same answer.
EInteractive lab
All six labs below work. Change the inputs, step forwards and backwards, and read the state panel — it explains every comparison. Lab 1 is the core visualizer; Labs 2–6 each isolate one idea from later sections.
FInternal working
F.1 Data organisation and memory
Binary search needs nothing but the sorted sequence and a few integers: lo, hi and mid. It never copies or modifies the array, so its auxiliary space is O(1) in the iterative form. [9] In CPython a list is an array of references, so a[mid] is a constant-time address computation followed by one comparison of the referenced objects. [22] Two consequences are easy to miss: (1) the comparison may be expensive (two long strings compare character by character), and (2) slicing — a[mid+1:] — copies elements, which silently turns an O(log n) search into O(n) (see Section L). [22]
F.2 Execution flow
- Initialise
lo = 0,hi = n − 1. - If
lo > hi, the interval is empty: return −1. - Compute
midand compareA[mid]with the target: equal → return mid; smaller →lo = mid + 1; larger →hi = mid − 1; loop.
hi − lo by at least 1 (in fact roughly halves it), which is the termination argument of Section G. [4]
In words, the classic algorithm runs these numbered steps [3][4]:
- Set the interval to the whole array:
lo = 0,hi = n − 1. - While the interval is non-empty (
lo ≤ hi), computemid = lo + (hi − lo) // 2. - Compare once. If
A[mid] == xyou are done. - If
A[mid] < x, thenA[lo..mid]are all< x: discard them withlo = mid + 1. - Otherwise
A[mid..hi]are all> x: discard them withhi = mid − 1. - If the loop exits, the interval is empty and
xis absent;lois its insertion point.
F.3 Two templates you must not mix
Almost every binary-search bug comes from mixing two different meanings of hi. Pick one template, and let its invariant dictate every line. [5][7]
lo, hi = 0, n − 1while lo <= hi:lo = mid + 1 or hi = mid − 1Invariant: if x is present, its index is in [lo, hi]. Empty when lo = hi + 1. Natural when you can stop on equality.
lo, hi = 0, nwhile lo < hi:lo = mid + 1 or hi = midInvariant: answer index is in [lo, hi], with hi = n meaning “none”. Ends when lo = hi — that is the answer. This is CPython’s
bisect_left. [7]F.4 State changes and edge cases
| Situation | What happens in the classic loop | Result |
|---|---|---|
| Empty array (n = 0) | hi = −1 < lo = 0; the loop body never runs. | −1, zero comparisons |
| One element | One probe at index 0. | 0 or −1 |
| Target smaller than every element | hi keeps moving left until hi = −1. | −1; insertion point lo = 0 |
| Target larger than every element | lo keeps moving right until lo = n. | −1; insertion point n |
| Duplicates | Stops at whichever copy a probe hits first. | Some matching index — not necessarily the first. Use lower bound for “first”. |
| Even-length interval | (lo + hi) // 2 picks the left of the two middles. | Harmless in the closed template; matters for lo = mid variants (Lab 6, Bug B). |
| Unsorted input | The discard step throws away the wrong half. | Undefined: may miss a present key. Python’s bisect assumes, and does not check, sortedness. [6] |
F.5 Inside Python’s bisect
CPython’s Lib/bisect.py implements bisect_left with the half-open template: while lo < hi: mid = (lo + hi) // 2; if a[mid] < x: lo = mid + 1 else: hi = mid, and raises ValueError if lo is negative. At the end of the file it imports a C accelerator, _bisect, which replaces those pure-Python definitions when available. [7] The functions only call __lt__, so any type with a consistent “less than” works; since Python 3.10 they accept a key= function, which is applied to the array elements but not to x. [6] Writing (lo + hi) // 2 is safe in Python because its integers have unlimited precision — there is no overflow to guard against, unlike in Java or C. [21][8]
GMathematical foundation
G.1 Correctness by loop invariant
- Initialisation. With lo = 0, hi = n−1 there are no indices < lo or > hi, so I holds vacuously.
- Maintenance. If A[mid] < x, sortedness gives A[i] ≤ A[mid] < x for all i ≤ mid, so setting lo = mid+1 keeps I. The case A[mid] > x is symmetric with hi = mid−1.
- Termination with an answer. If A[mid] = x we return a correct index. If the loop exits, then lo = hi + 1, every index is either < lo or > hi, and by I none holds x — so −1 is correct, and lo is the insertion point.
- Progress. Since lo ≤ mid ≤ hi, both updates strictly decrease the non-negative quantity hi − lo + 1, so the loop runs a finite number of times.
The half-open template uses the invariant “A[i] < x for i < lo and A[i] ≥ x for i ≥ hi”; CP-Algorithms phrases the same idea as maintaining A_L ≤ k < A_R across the loop. [5] The proof above is the author’s standard textbook argument, written out for this chapter.
G.2 How many comparisons? The recurrence
Let C(n) be the worst-case number of three-way comparisons on an interval of n elements. One comparison at the middle leaves at most ⌊n/2⌋ elements (the larger side of the remaining n − 1), so
Unrolling: each halving removes one binary digit of n, and n has ⌊log₂ n⌋ + 1 digits. This matches Princeton’s Proposition B (“no more than lg N + 1 compares”) and the Master Theorem case T(n) = T(n/2) + Θ(1) = Θ(log n). [3][25] The companion code verifies C(n) = ⌊log₂ n⌋ + 1 exhaustively for every n < 300 (Python’s n.bit_length()).
G.3 Why nobody can do better: the decision-tree lower bound
- Each circle is a comparison of
xwithA[mid]; its two children are what happens next on “<” or “>”. - A search ends at a circle (found) or at one of the n + 1 = 8 squares (absent, falling in a gap between keys).
- The green path is a search for 35: compare with 40, then 20, then 30, then fall into the gap (30, 40).
MIT 6.006 states the result as: any decision tree with n nodes has height at least ⌈lg(n+1)⌉ − 1, hence searching among n preprocessed items needs Ω(lg n) comparisons and binary search is optimal in the comparison model. [2][1] Since ⌈log₂(n+1)⌉ = ⌊log₂ n⌋ + 1 for every n ≥ 1, binary search meets the bound exactly, not just asymptotically. Hash tables escape the bound only because they leave the comparison model: they compute an address from the key. [2]
G.4 Average case
For a successful search with every key equally likely, the cost is the average depth of a node in the decision tree. When n = 2^k − 1 the tree is perfect: level d (counting the root as 1) has 2^{d−1} nodes, so
For n = 7: (2·8 + 1)/7 = 17/7 ≈ 2.43 comparisons, versus a worst case of 3. So the average is only about one comparison below the worst case — binary search is Θ(log n) on average too. (This derivation is the author’s; the Wikipedia survey reports the same near-log₂ n behaviour from Knuth.) [9]
G.5 The monotone-predicate view
Searching for x in a sorted array is the special case p(i) = [A[i] ≥ x]; the array’s sortedness is precisely what makes p monotone. CP-Algorithms makes the same generalisation: replace the comparison with “an arbitrary monotonous predicate”. [5] That single observation powers Section M’s “binary search on the answer” problems.
HOperations & complexity analysis
Assumptions: A is a sorted Python list of length n; comparing two keys costs O(1); indexing costs O(1). [22]
| Operation | Best case | Average case | Worst case | Auxiliary space |
|---|---|---|---|---|
| Find x (classic, iterative) | Θ(1) | Θ(log n) | Θ(log n) | Θ(1) |
| Find x (recursive) | Θ(1) | Θ(log n) | Θ(log n) | Θ(log n) stack |
Lower / upper bound (bisect_left/right) | Θ(log n) | Θ(log n) | Θ(log n) | Θ(1) |
| First/last occurrence, count of x | Θ(log n) | Θ(log n) | Θ(log n) | Θ(1) |
| Range count “keys in [a, b]” | Θ(log n) | Θ(log n) | Θ(log n) | Θ(1) |
Insert keeping order (insort) | Θ(log n) (append at end) | Θ(n) | Θ(n) | Θ(1) amortized |
| Build: sort once before searching | Θ(n)* | Θ(n log n) | Θ(n log n) | O(n) |
| Search on the answer (range R, check costs C) | Θ(C · log R) | Θ(C · log R) | Θ(C · log R) | space of the check |
* Python’s Timsort exploits existing order and needs as few as n − 1 comparisons on already-sorted input; [27] the general comparison-sort bound is Θ(n log n). [2]
Reasoning behind each entry
- Find, best case Θ(1): the first probe may hit the target. Worst case Θ(log n): the recurrence of G.2. Both bounds are tight, so we may write Θ(log n) for the worst case: O(log n) from the recurrence and Ω(log n) from the decision tree. [3][2]
- Average Θ(log n): G.4 — about one comparison less than the worst case. [9]
- Bounds have no early exit:
bisect_leftnever stops on equality, so it always runs about ⌈log₂(n+1)⌉ iterations — best = worst = Θ(log n). [7] - Recursive space: each call adds a stack frame and there are at most ⌊log₂ n⌋ + 1 calls — only about 31 frames for a billion elements, far below Python’s default recursion limit. [26]
- insort Θ(n): the search is O(log n) but “is dominated by the slow O(n) insertion step”, because
list.insertshifts the tail. [6][22] Princeton notes that inserting N keys into an ordered array costs ~N² array accesses in the worst case. [3] - Search on the answer: ⌈log₂ R⌉ predicate evaluations, each costing C (often O(n) to scan the input). [5]
insort inserts at the end and list.append’s amortized O(1) applies; for arbitrary keys each insertion is genuinely Θ(n). Sorting once and then answering q queries costs O(n log n + q log n), versus O(qn) for repeated linear search, so the one-off sort pays for itself once the number of queries exceeds roughly log n. [22]Time–space trade-offs
Binary search is the low-memory end of the searching spectrum: O(1) extra space and no per-key overhead. A hash set spends extra memory (empty slots, stored hashes) to reach expected O(1) lookups but loses order. A balanced BST spends pointer memory to make insertion O(log n). Layout tricks such as the Eytzinger order (Section N) spend a one-off permutation to make each probe more cache-friendly. [2][15]
Theory versus real Python behaviour
bisectruns in C (the_bisectaccelerator), so it is many times faster per step than a hand-written Python loop; prefer it in production code. [7]- With
key=, the key function is called on every probed element on every call; for expensive keys the docs recommend searching a precomputed list of keys. [6] - For small lists, a linear scan in C (
x in lst) can beat a Python-level binary search despite the worse asymptotics — measure before micro-optimising. - On very large arrays, each probe of a plain binary search can touch a different cache line, so memory latency, not comparisons, dominates the running time. [15]
IPython implementation
All code in this section comes from one companion module, binary_search.py, which was executed with Python 3.13; every output shown is real output. The module also contains a randomized self-test that checks each function against Python’s bisect and brute force on thousands of inputs.
I.1 Classic iterative binary search (from scratch)
def binary_search(a: Sequence, target) -> int:
"""Return an index i with a[i] == target, or -1 if target is absent.
Precondition: a is sorted in non-decreasing order.
Invariant: if target is in a, its index lies in the closed range [lo, hi].
"""
lo, hi = 0, len(a) - 1
while lo <= hi: # range [lo, hi] is non-empty
mid = lo + (hi - lo) // 2 # overflow-safe form (habit from C/Java)
if a[mid] == target:
return mid # found
elif a[mid] < target:
lo = mid + 1 # target can only be to the right
else:
hi = mid - 1 # target can only be to the left
return -1 # range became empty: absent
Line-by-line
| Line | Why it is there |
|---|---|
lo, hi = 0, len(a) - 1 | Closed interval covering the whole list. For an empty list hi = −1, so the loop is skipped. |
while lo <= hi | The interval [lo, hi] is non-empty exactly when lo ≤ hi. Using < here would skip the last candidate (Lab 6, Bug A). |
mid = lo + (hi - lo) // 2 | Middle index, rounding down. Mathematically equal to (lo + hi) // 2; the form never exceeds hi in fixed-width languages, which is Bloch’s fix for the overflow bug. Python ints cannot overflow, but the habit transfers. [8][4] |
if a[mid] == target | Early exit — the source of the Θ(1) best case. |
lo = mid + 1 / hi = mid - 1 | Discard mid and its whole side. The ±1 guarantees progress; without it the loop can stall (Lab 6, Bug B). |
return -1 | Interval empty: the invariant proves the target is absent. At this point lo is the insertion point. |
I.2 Recursive version
def binary_search_rec(a: Sequence, target, lo: int = 0, hi: Optional[int] = None) -> int:
if hi is None:
hi = len(a) - 1
if lo > hi: # base case: empty range
return -1
mid = lo + (hi - lo) // 2
if a[mid] == target:
return mid
if a[mid] < target:
return binary_search_rec(a, target, mid + 1, hi)
return binary_search_rec(a, target, lo, mid - 1)
Same invariant; the interval is passed as parameters instead of being updated in place. Passing indices — never slices like a[mid+1:] — keeps each call O(1). Recursion depth is at most ⌊log₂ n⌋ + 1, so stack usage is O(log n). Stanford’s CS106B uses exactly this recursive shape to introduce binary search. [23]
I.3 Boundary searches (half-open template)
def lower_bound(a: Sequence, x) -> int:
"""First index i with a[i] >= x (len(a) if none). Same as bisect_left."""
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < x:
lo = mid + 1 # a[mid] is too small: answer is right of mid
else:
hi = mid # a[mid] >= x: mid might be the answer
return lo
def upper_bound(a: Sequence, x) -> int:
"""First index i with a[i] > x (len(a) if none). Same as bisect_right."""
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] <= x:
lo = mid + 1
else:
hi = mid
return lo
def search_range(a: Sequence, x) -> List[int]:
"""[first, last] index of x in sorted a, or [-1, -1]. (LeetCode 34)"""
i = lower_bound(a, x)
if i == len(a) or a[i] != x:
return [-1, -1]
return [i, upper_bound(a, x) - 1]
def count_occurrences(a: Sequence, x) -> int:
return upper_bound(a, x) - lower_bound(a, x)
These mirror CPython’s own bisect_left/bisect_right line for line. [7] Note hi = mid (not mid − 1): when a[mid] ≥ x, mid itself may be the answer, so it must stay inside [lo, hi]. Progress is still guaranteed because mid < hi whenever lo < hi.
I.4 The general tool: first True of a monotone predicate
def first_true(lo: int, hi: int, pred: Callable[[int], bool]) -> int:
"""Smallest integer t in [lo, hi) with pred(t) True, or hi if none.
Requires pred to be monotone: False ... False True ... True.
"""
while lo < hi:
mid = (lo + hi) // 2
if pred(mid):
hi = mid
else:
lo = mid + 1
return lo
Every boundary search is first_true with a particular predicate: lower_bound(a, x) == first_true(0, len(a), lambda i: a[i] >= x). This is Topcoder’s “main theorem” turned into code. [11][5]
I.5 Sample inputs and expected outputs
Running the module’s demo prints (excerpt, unedited):
>>> a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
>>> binary_search(a, 23)
5
>>> binary_search(a, 40)
-1
>>> binary_search_rec(a, 91)
9
>>> binary_search([], 5)
-1
>>> lower_bound([1, 2, 2, 2, 3, 5, 8], 2)
1
>>> upper_bound([1, 2, 2, 2, 3, 5, 8], 2)
4
>>> count_occurrences([1, 2, 2, 2, 3, 5, 8], 2)
3
>>> search_range([1, 2, 2, 2, 3, 5, 8], 2)
[1, 3]
>>> search_range([1, 2, 2, 2, 3, 5, 8], 4)
[-1, -1]
>>> lower_bound([1, 2, 2, 2, 3, 5, 8], 4)
5
>>> first_true(0, 100, lambda t: t * t >= 50)
8
>>> isqrt_floor(10**18)
1000000000
I.6 Dry-run tables
These tables were printed by the instrumented function binary_search_trace / lower_bound_trace in the module.
Classic search, a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], target 23
| Iter. | lo | hi | mid | a[mid] | Compare | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 9 | 4 | 16 | 16 < 23 | lo = 5 |
| 2 | 5 | 9 | 7 | 56 | 56 > 23 | hi = 6 |
| 3 | 5 | 6 | 5 | 23 | equal | return 5 |
Same array, target 40 (absent)
| Iter. | lo | hi | mid | a[mid] | Compare | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 9 | 4 | 16 | 16 < 40 | lo = 5 |
| 2 | 5 | 9 | 7 | 56 | 56 > 40 | hi = 6 |
| 3 | 5 | 6 | 5 | 23 | 23 < 40 | lo = 6 |
| 4 | 6 | 6 | 6 | 38 | 38 < 40 | lo = 7 |
| — | 7 | 6 | lo > hi: interval empty | return −1 (insertion point 7) | ||
lower_bound([1, 2, 2, 2, 3, 5, 8], 2)
| Iter. | lo | hi | mid | a[mid] | Test | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 7 | 3 | 2 | a[mid] ≥ 2 | hi = 3 |
| 2 | 0 | 3 | 1 | 2 | a[mid] ≥ 2 | hi = 1 |
| 3 | 0 | 1 | 0 | 1 | a[mid] < 2 | lo = 1 |
| — | 1 | 1 | lo == hi | return 1 | ||
Notice that iteration 1 found a 2 at index 3 but kept going — a boundary search never stops early, because an equal element is not necessarily the first one.
I.7 Edge cases and error handling
def safe_binary_search(a, target, *, check_sorted: bool = False) -> int:
if not hasattr(a, "__getitem__") or not hasattr(a, "__len__"):
raise TypeError("binary search needs a random-access sequence (list, tuple, range, array)")
if check_sorted and any(a[i] > a[i + 1] for i in range(len(a) - 1)):
raise ValueError("input is not sorted in non-decreasing order")
return binary_search(a, target)
- Empty input returns −1 (classic) or 0 (bounds) without touching the list.
- Sortedness is a precondition. Checking it costs O(n) and would destroy the point of an O(log n) search, so it is opt-in (
check_sorted=True) — useful in tests, not in hot paths. Python’sbisectlikewise trusts the caller. [6] - Non-indexable input (a
set, a generator) raisesTypeError: binary search needs random access. - Mixed types (e.g.
[1, "a"]) raiseTypeErrorfrom<in Python 3 — a feature, not a bug. - Floating-point keys:
NaNcompares false with everything and breaks the ordering; filter it out before sorting.
I.8 Built-in Python alternatives
from bisect import bisect_left, bisect_right, insort
a = [1, 2, 2, 2, 3, 5, 8]
bisect_left(a, 2) # 1 first index with a[i] >= 2
bisect_right(a, 2) # 4 first index with a[i] > 2
bisect_right(a, 2) - bisect_left(a, 2) # 3 copies of 2
def index(a, x): # recipe from the bisect docs: leftmost exact match
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
insort(a, 4) # a == [1, 2, 2, 2, 3, 4, 5, 8]; O(n) because of the shift
# key= (Python 3.10+): search records by a field. The key is NOT applied to x.
movies = [("Casablanca", 1942), ("Vertigo", 1958), ("Alien", 1979)]
bisect_left(movies, 1958, key=lambda m: m[1]) # 1
# Grade lookup from the docs: breakpoints map scores to letters
def grade(score, breakpoints=[60, 70, 80, 90], grades="FDCBA"):
return grades[bisect_right(breakpoints, score)]
[grade(s) for s in (33, 99, 77, 70, 89, 90, 100)] # ['F', 'A', 'C', 'C', 'B', 'A', 'A']
All of these behaviours — the insertion-point semantics, the key rule, the index and grade recipes, and insort being dominated by the O(n) insertion — are documented in the bisect module reference. [6] Other languages offer the same tools: Java’s Arrays.binarySearch returns −(insertion point) − 1 when the key is absent, [19] and C++ provides std::lower_bound/upper_bound, which only require the range to be partitioned with respect to the value. [20]
I.9 Comparison of implementations
| Implementation | Returns | Time | Extra space | Use when |
|---|---|---|---|---|
Iterative closed (binary_search) | some index of x, or −1 | O(log n) | O(1) | Distinct keys, membership + position. |
Recursive (binary_search_rec) | same | O(log n) | O(log n) | Teaching; divide-and-conquer style code. |
lower_bound / upper_bound | boundary index 0…n | O(log n) | O(1) | Duplicates, insertion points, ranges, predecessor/successor. |
first_true(lo, hi, pred) | first t with pred(t) | O(C · log R) | that of pred | Binary search on the answer. |
bisect module | boundary index | O(log n) | O(1) | Production Python: C speed, tested. [7] |
x in lst / lst.index(x) | bool / first index | O(n) | O(1) | Unsorted or tiny lists. [22] |
x in set_ | bool | O(1) avg | O(n) | Pure membership, no order needed. [22] |
JReal-world applications
Binary search shows up wherever data is kept in order, and — more broadly — wherever a yes/no answer flips exactly once along an ordered axis such as time, version number, capacity or price.
git bisect: binary search over history- Commit c0 is known good and c16 known bad. The predicate “does this commit have the bug?” is False…False True…True along history — monotone.
- Git checks out the middle commit (c8) for you to test: bad → the culprit is in c1…c8. Then c4: good → c5…c8. Then c6: bad → c5…c6. Then c5: good.
- Answer: c6 is the first bad commit, found with 4 tests instead of up to 16.
git bisect describes it as using “a binary search algorithm to find which commit in your project’s history introduced a bug”; git bisect run <script> automates the predicate. [16]
| Domain | How binary search is used |
|---|---|
| Developer tooling | git bisect finds the first bad commit between a known-good and a known-bad revision by testing midpoints. [16] |
| Databases & storage engines | LevelDB stores sorted keys in blocks; the end of each block holds the offsets of “restart points”, which the source code says “can be used to do a binary search when looking for a particular key”. [17] Sorted-array symbol tables are the textbook basis of ordered indexes. [3] |
| Operating systems | The Linux kernel ships a generic bsearch() in lib/bsearch.c for sorted in-kernel arrays, parameterised by element size and comparison function. [18] |
| Language runtimes | Python’s bisect, Java’s Arrays.binarySearch, and C++’s lower_bound/upper_bound/equal_range are standard-library binary searches. [6][19][20] |
| Backend engineering | Tiered lookups — prices, tax brackets, grade boundaries — map a number to a band with bisect_right(breakpoints, value), exactly the “grade” recipe in the Python docs. [6] ILLUSTRATIVE A service keeping an in-memory sorted list of event timestamps answers “how many requests in the last 60 s?” as bisect_right(ts, now) − bisect_left(ts, now − 60). |
| Networking | ILLUSTRATIVE IP-to-region tables are sorted, non-overlapping address ranges; the range containing an address is found with a predecessor query: i = bisect_right(starts, ip) − 1, then check ip ≤ ends[i]. (Production routers use specialised tries for longest-prefix match.) |
| Distributed systems | ILLUSTRATIVE In a consistent-hashing ring stored as a sorted list of node positions, the node that owns a key is the first position ≥ hash(key) — a lower-bound query, wrapping to index 0 at the end. |
| Search engines | ILLUSTRATIVE Intersecting two sorted posting lists of very different lengths is done by galloping through the long list — exponential search (Section N), which Bentley and Yao introduced for unbounded sorted tables. [12] |
| Numerical & capacity planning | Bisection finds a root or threshold of a monotone function to any precision δ in O(log((R−L)/δ)) steps. [5] ILLUSTRATIVE “What is the smallest number of servers that keeps p99 latency under 200 ms?” is binary search on the answer, if latency falls monotonically with servers. |
KComparison with alternatives
| Method | Requires | Search | Insert | Ordered queries? | Extra space |
|---|---|---|---|---|---|
| Linear search | nothing | O(n) | O(1) append | by full scan | O(1) |
| Binary search on sorted array | sorted, random access | Θ(log n) | O(n) | yes, O(log n) | O(1) |
| Hash set / dict | hashable keys | O(1) expected | O(1) expected amortized | no | O(n) |
| Balanced BST | comparable keys | O(log n) | O(log n) | yes | O(n) pointers |
| Interpolation search | sorted numeric, near-uniform keys | O(log log n) avg, O(n) worst | O(n) | yes | O(1) |
| Exponential (galloping) search | sorted, maybe unbounded | O(log i), i = answer position | O(n) | yes | O(1) |
Sources: sorted array vs hash table vs direct access [2]; ordered-array costs [3]; interpolation search [13][14]; exponential search [12]; Python dict/set costs [22].
- Only exact membership, no order needed → a hash set wins (expected O(1)).
- Need predecessor/successor/range queries on mostly static data → sort once and binary search.
- Need ordered queries and frequent inserts/deletes → a balanced BST (or a B-tree in storage).
- Tiny or one-off unsorted data → just scan; sorting costs more than it saves.
When should binary search be avoided?
- The data is unsorted and you will search only once or twice. Sorting costs Θ(n log n); one linear scan costs Θ(n).
- Inserts and deletes are as frequent as lookups. Each insert into a sorted array is O(n). [6]
- No random access (linked lists, streams). Use a tree, skip list or a different index.
- Only exact-match lookups on hashable keys: a
dict/setis simpler and faster; the bisect documentation says the same. [6] - The predicate is not monotone. Binary search silently returns garbage; prove monotonicity first. [11]
LCommon mistakes & misconceptions
Bentley’s observation that most professional programmers wrote an incorrect binary search [9] is a good reason to study the failure modes one by one. Lab 6 lets you run four of them.
1. Loop condition that does not match the interval (Bug A)
lo, hi = 0, len(a) - 1 # closed interval
while lo < hi: # stops when one candidate is left
...
return -1 # never checks a[lo]!
# binary_search([1, 3], 3) returns -1lo, hi = 0, len(a) - 1 # closed interval
while lo <= hi: # non-empty while lo <= hi
...
return -12. Not making progress: lo = mid (Bug B)
while lo < hi:
mid = (lo + hi) // 2 # lower middle
if a[mid] <= x:
lo = mid # when hi == lo + 1, mid == lo
else: # → nothing changes: infinite loop
hi = mid - 1while lo < hi:
mid = (lo + hi + 1) // 2 # UPPER middle when lo = mid
if a[mid] <= x:
lo = mid
else:
hi = mid - 1
# or simply: upper_bound(a, x) - 1Rule: if a branch sets lo = mid, round mid up; if it sets hi = mid, round down. Otherwise a two-element interval never shrinks.
3. Wrong initial hi (Bug C)
hi = len(a) belongs to the half-open template. Combined with while lo <= hi it eventually probes a[len(a)] and raises IndexError when the target exceeds every element.
4. Midpoint overflow in fixed-width languages (Bug D)
int mid = (low + high) / 2; // low + high may exceed 2^31 - 1int mid = low + (high - low) / 2;
int mid = (low + high) >>> 1; // Java unsigned shiftBloch reported that this exact line broke Java’s Arrays.binarySearch once arrays reached about 230 elements; the sum overflows to a negative number and the program crashes with an index exception. [8] Python is immune because its integers have unlimited precision, [21] and CPython’s own bisect uses (lo + hi) // 2. [7]
5. Slicing in recursion
def bs(a, x):
if not a: return False
m = len(a) // 2
if a[m] == x: return True
return bs(a[m+1:], x) if a[m] < x else bs(a[:m], x)
# each slice copies → O(n) total time and space,
# and the original index is lost# pass indices, not slices
def bs(a, x, lo=0, hi=None):
if hi is None: hi = len(a) - 1
if lo > hi: return -1
m = (lo + hi) // 2
...Python slicing a list of length k costs O(k), so the copies sum to n/2 + n/4 + … = O(n). [22]
6. Assuming the classic search returns the first occurrence
On [2, 2, 2, 2, 2] the classic loop returns index 2 — the first probe. If the question is “first” or “last” occurrence, use bisect_left / bisect_right − 1 (LeetCode 34). [6]
7. Searching unsorted data, or sorting for a single query
Binary search on unsorted input is not “slower” — it is wrong: it can miss elements that are present. And sort + one search is Θ(n log n), worse than one Θ(n) scan. “Binary search is O(log n)” is true only after the data is sorted.
8. Complexity misconceptions
- “O(log n) on a linked list”: comparisons are O(log n) but reaching each middle node is a walk, so total time is O(n).
- “Log base matters”: log₂ n and log₁₀ n differ by a constant factor, so both are O(log n); the base matters only for exact comparison counts.
- “Ternary search is faster because it cuts into thirds”: it makes two comparisons per step, about 2 log₃ n ≈ 1.26 log₂ n comparisons — more than binary search. (Author’s arithmetic: 2/ log₂ 3 ≈ 1.26.)
9. Answer-space bounds that are not valid
In Koko (Lab 4), starting the speed range at 0 causes division by zero, and an upper end that is not feasible returns a wrong answer. Pick lo = smallest conceivable answer and hi = a value known to satisfy the predicate (max(piles)).
10. Floating-point loops that never end
while hi - lo > 1e-12: # may spin forever when
mid = (lo + hi) / 2 # lo and hi are adjacent floats
...for _ in range(100): # 2**-100 shrink: plenty
mid = (lo + hi) / 2
...11. Interview mistakes
- Coding before saying what
loandhimean. State the invariant aloud first. - Not testing n = 0, 1, 2, target below the minimum, above the maximum, and duplicates.
- Reaching for binary search on a non-monotone condition (e.g. searching a rotated array with the plain algorithm).
- Forgetting to mention that Python’s
bisectexists — interviewers usually accept it once you can explain it.
MInterview preparation
M.1 The six binary-search patterns
| Pattern | Signal in the problem | Core move | Typical problems |
|---|---|---|---|
| Exact search | sorted array, “return the index” | closed template, stop on equality | 704 Binary Search |
| Boundary | “first / last / insert position / how many” | bisect_left, bisect_right | 35, 34, 278 First Bad Version |
| Answer space | “minimum capacity / speed / largest minimum…”, plus a cheap feasibility check | first_true over candidate answers | 875, 1011, 410, 1283 |
| Partially sorted | “rotated”, “mountain”, “bitonic” | decide which half is sorted / which way is uphill | 33, 153, 162 |
| Implicit array | 2-D sorted matrix, integer square root | map index ↔ value with arithmetic | 74, 69 |
| Partition search | “median / k-th of two sorted arrays” | binary search a cut position, check cross inequalities | 4 |
The answer-space pattern rests on the monotone-predicate theorem: design a predicate that is False…False True…True and search for its first True. [11][5]
M.2 Common interview questions
- What preconditions does binary search need, and what breaks if they fail?
- What is the loop invariant of your implementation? Why does it terminate?
- Why
lo + (hi − lo) // 2? Is it needed in Python? - How do you find the first and last occurrence of a value with duplicates?
- Prove binary search is optimal for comparison-based search.
- How would you search an array whose length you do not know?
- When would you prefer a hash table, a BST, or binary search?
M.3 Coding exercises
1. Binary Search EASY
LeetCode 704 — return the index of target in a sorted array of distinct integers, or −1.
Hint
Closed interval,while lo <= hi, move past mid on each side.Solution & complexity
Exactly binary_search from I.1. Time O(log n), space O(1).
2. Search Insert Position EASY
LeetCode 35 — return the index of target, or where it would be inserted.
Hint
Both cases are the same number: the first index withnums[i] ≥ target.Solution & complexity
def search_insert(nums, target):
return lower_bound(nums, target) # == bisect.bisect_left(nums, target)
O(log n) time, O(1) space. The closed-template loop also works: return lo after it exits (Figure D.4).
3. Find First and Last Position of Element MEDIUM
LeetCode 34 — return [first, last] of target, or [-1, -1], in O(log n).
Hint
Two boundary searches: lower bound and upper bound − 1.Solution & complexity
def search_range(a: Sequence, x) -> List[int]:
"""[first, last] index of x in sorted a, or [-1, -1]. (LeetCode 34)"""
i = lower_bound(a, x)
if i == len(a) or a[i] != x:
return [-1, -1]
return [i, upper_bound(a, x) - 1]
Two O(log n) searches. A common wrong answer finds one copy and then scans outward — O(n) on [2, 2, …, 2].
4. Search in Rotated Sorted Array MEDIUM
LeetCode 33 — distinct values, sorted then rotated at an unknown pivot; find target in O(log n). Try it in Lab 5.
Hint
At any mid, at least one of[lo..mid] and [mid..hi] is sorted. Check whether the target lies inside the sorted half’s value range.Solution & complexity
def search_rotated(nums: Sequence[int], target: int) -> int:
"""LeetCode 33 — distinct values, sorted then rotated."""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # left half [lo..mid] is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half [mid..hi] is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
Each step still discards half: O(log n) time, O(1) space. With duplicates (LeetCode 81) the case nums[lo] == nums[mid] == nums[hi] cannot be decided, and the worst case degrades to O(n).
5. Koko Eating Bananas MEDIUM
LeetCode 875 — smallest integer speed k so that Σ⌈pᵢ/k⌉ ≤ h. Watch it in Lab 4.
Hint
Hours needed only go down as k goes up, so “can finish at speed k” is monotone on [1, max(piles)].Solution & complexity
def min_eating_speed(piles: Sequence[int], h: int) -> int:
"""LeetCode 875 — Koko eating bananas: smallest k finishing within h hours."""
def hours(k: int) -> int:
return sum((p + k - 1) // k for p in piles) # ceil(p / k)
return first_true(1, max(piles) + 1, lambda k: hours(k) <= h)
O(n · log M) time where M = max(piles), O(1) extra space. Output for [3, 6, 7, 11], h = 8: 4.
6. Find Peak Element MEDIUM
LeetCode 162 — return the index of any element strictly greater than its neighbours, in O(log n).
Hint
Ifnums[mid] < nums[mid+1] you are walking uphill to the right, and a peak must exist on that side.Solution & complexity
def find_peak(nums: Sequence[int]) -> int:
"""LeetCode 162 — index of any element greater than its neighbours."""
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < nums[mid + 1]:
lo = mid + 1 # uphill to the right: a peak exists there
else:
hi = mid
return lo
The array is not sorted, but the predicate “nums[i] > nums[i+1]” has a guaranteed True to the right of any uphill step — enough for a correct halving. O(log n).
7. Median of Two Sorted Arrays HARD
LeetCode 4 — median of two sorted arrays in O(log(m + n)).
Hint 1
Choose how many elements i the left half takes from the shorter array A; then j = half − i come from B.Hint 2
The cut is correct iff A[i−1] ≤ B[j] and B[j−1] ≤ A[i]. If A[i−1] > B[j], i is too big — that is the monotone predicate.Solution & complexity
def median_two_sorted(A: Sequence[int], B: Sequence[int]) -> float:
"""LeetCode 4 — O(log(min(m, n))) partition search."""
if len(A) > len(B):
A, B = B, A
m, n = len(A), len(B)
if m + n == 0:
raise ValueError("both arrays are empty")
half = (m + n + 1) // 2
lo, hi = 0, m
NEG, POS = float("-inf"), float("inf")
while lo <= hi:
i = (lo + hi) // 2 # elements taken from A
j = half - i # elements taken from B
a_left = A[i - 1] if i > 0 else NEG
a_right = A[i] if i < m else POS
b_left = B[j - 1] if j > 0 else NEG
b_right = B[j] if j < n else POS
if a_left <= b_right and b_left <= a_right:
if (m + n) % 2:
return float(max(a_left, b_left))
return (max(a_left, b_left) + min(a_right, b_right)) / 2
if a_left > b_right:
hi = i - 1
else:
lo = i + 1
raise AssertionError("unreachable for sorted inputs")
Binary search over i ∈ [0, min(m, n)]: O(log min(m, n)) time, O(1) space. Tested against brute-force merging on 4 000 random inputs.
8. Split Array Largest Sum HARD
LeetCode 410 — split nums into k non-empty contiguous parts minimising the largest part sum.
Hint
Guess a limit L. Greedily cut whenever the running sum would exceed L. If that needs ≤ k parts, any larger L also works.Solution & complexity
def split_array(nums: Sequence[int], k: int) -> int:
"""LeetCode 410 — minimise the largest sum when splitting into k parts."""
def parts(limit: int) -> int:
cnt, cur = 1, 0
for x in nums:
if cur + x > limit:
cnt, cur = cnt + 1, 0
cur += x
return cnt
return first_true(max(nums), sum(nums) + 1, lambda L: parts(L) <= k)
Answer range [max(nums), sum(nums)]; O(n log S) time with S = sum(nums). For [7, 2, 5, 10, 8], k = 2 the answer is 18 ([7,2,5] | [10,8]). Verified against exhaustive search over all cut positions.
lo and hi mean and which template you use. (3) Write the loop. (4) Walk one 2-element example by hand to prove there is no infinite loop. (5) State O(log n) or O(C log R).★Practice problems
For each problem, state the search space and the monotone yes/no question before writing the loop. There are 38 problems, grouped by level and topic: 8 easy, 15 medium and 15 hard. Each link opens the problem on the platform where you can submit and test your solution. Tick a problem when you have solved it, and use “My solution” to save your code, approach, complexity and notes to revise later.
Basic8 problems
Direct applications of this chapter’s core idea.
Binary Search
Halve a sorted search space; lower and upper bounds; rotated arrays.
Intermediate15 problems
The pattern combined with one more idea, or applied to a less obvious setup.
Binary Search
Halve a sorted search space; lower and upper bounds; rotated arrays.
Binary Search on Answers
Search over the answer itself using a monotone yes/no check.
Advanced15 problems
Harder variants that need the full toolkit and careful invariants.
Binary Search
Halve a sorted search space; lower and upper bounds; rotated arrays.
Binary Search on Answers
Search over the answer itself using a monotone yes/no check.
NAdvanced concepts
N.1 Exponential (galloping) search — when n is unknown or the answer is near the front
Probe indices 1, 2, 4, 8, … until you overshoot the target, then binary search inside the last bracket. Bentley and Yao introduced this family for searching unbounded ordered tables and showed it is almost optimal. [12] If the answer sits at position i, the cost is O(log i) rather than O(log n).
def exponential_search(a: Sequence, target) -> int:
"""Galloping search: find a bracket [bound/2, bound] then binary search it."""
if not a:
return -1
bound = 1
while bound < len(a) and a[bound] < target:
bound *= 2
lo, hi = bound // 2, min(bound, len(a) - 1)
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
N.2 Interpolation search — guessing smarter than the middle
Instead of the middle, probe where the key should be if values are evenly spread: pos = lo + (x − A[lo]) · (hi − lo) / (A[hi] − A[lo]). Perl, Itai and Avni proved an average of about log log n probes for uniformly distributed keys, [13] but the worst case for skewed data is O(n), and the extra arithmetic often makes it no faster than binary search in practice. [14]
N.3 Bisection on real numbers
For a continuous monotone function, binary search on an interval approximates the crossing point to within ±δ in O(log((R − L)/δ)) iterations. [5] Using a fixed iteration count avoids floating-point non-termination:
def sqrt_real(x: float, eps: float = 1e-9) -> float:
"""Bisection on real numbers: 100 halvings shrink any interval by 2**-100."""
if x < 0:
raise ValueError("x must be non-negative")
lo, hi = 0.0, max(1.0, x)
for _ in range(100):
mid = (lo + hi) / 2
if mid * mid < x:
lo = mid
else:
hi = mid
return hi
Output: sqrt_real(2) = 1.414213562373.
N.4 Making each probe cheaper: memory layout
Khuong and Morin benchmarked layouts for comparison-based searching and concluded that for small arrays a well-implemented binary search on sorted order is best, while for larger arrays the Eytzinger (breadth-first, heap-like) layout with branch-free code and prefetching performed best. [15] In the Eytzinger layout the root is at index 1 and the children of k are at 2k and 2k + 1, so the first few levels share cache lines. The Wikipedia survey also notes that plain binary search on large power-of-two arrays can thrash caches and TLBs. [9]
N.5 Many searches at once
- Fractional cascading (Chazelle & Guibas, 1986) speeds up searching for the same key in k related sorted lists from O(k log n) to O(log n + k) by threading pointers between them. [24][9]
- Parallel binary search answers many independent “first time the predicate becomes true” queries together, sweeping the shared process once per halving round. [5]
N.6 Variants with history
- Deferred equality test. Bottenbruch’s 1962 ALGOL version tested equality only at the end, using one comparison per iteration at the cost of about one extra iteration — the ancestor of today’s
bisect_left. [9] - Uniform binary search stores the sequence of step sizes in a precomputed table instead of computing midpoints. [9][10]
- Noisy binary search tolerates comparisons that sometimes lie, at the price of extra comparisons governed by an entropy bound. [9]
ONotebook-ready summary
First, the whole idea on one page — copy this sheet into your notebook. The detailed revision notes follow it.
Find x in a sorted array by checking the middle of the part that could still hold it, then keeping only the correct half.
Needs: sorted order + O(1) indexing (array, not linked list).
“If x is in A, it is inside [lo, hi].”
A[mid] > x → hi = mid − 1
Loop while lo ≤ hi. Exit ⇒ absent, and lo = insertion point.
- lo < hi with closed [lo, hi] → misses last one
- lo = mid with lower mid → infinite loop
- (lo+hi)/2 overflow in Java/C
- slicing a[mid:] → O(n)
3 comparisons for 10 items → index 5
bisect_right = first a[i] > x
count(x) = right − left · last = right − 1
Binary search finds the boundary where a monotone yes/no question flips: F F F T T T.
| best | O(1) |
| avg / worst | O(log n) |
| space (loop) | O(1) |
| insort | O(n) |
n → n/2 → n/4 → … → 1
⌊log₂ n⌋ + 1 compares
10⁶ → 20 · 10⁹ → 30
from bisect import bisect_left, bisect_right, insort
key= since 3.10
- 🔍sorted lookups & ranges
- 🐞git bisect
- 📈search on the answer
- 🗄️DB / storage indexes
1 · Formal definition
- Given sorted
A[0..n−1]and key x, keep an interval that must contain x; compare x with A[mid]; keep one half; stop on match or empty interval.
2 · Core concept
- One comparison with the middle eliminates half the candidates because of sortedness.
- Really: find the first True of a monotone predicate.
3 · Key properties
- Preconditions: sorted, random access.
- Worst case ⌊log₂ n⌋ + 1 = ⌈log₂(n+1)⌉ comparisons — optimal in the comparison model (decision tree).
- Iterative space O(1); recursive O(log n).
4 · Two templates
- Closed:
hi = n−1,while lo <= hi,lo = mid+1/hi = mid−1. - Half-open:
hi = n,while lo < hi,lo = mid+1/hi = mid→ returns boundary. lo = mid⇒ use upper mid(lo+hi+1)//2.
5 · Important operations
- find · lower bound · upper bound · count = ub − lb · predecessor = A[ub(x)−1] · successor = A[lb(x)] · range count = ub(R) − lb(L).
6 · Python syntax
i = bisect_left(a, x); found = i < len(a) and a[i] == xinsort(a, x)keeps a sorted (O(n)).
7 · Applications
- Sorted indexes, git bisect, LevelDB blocks, kernel bsearch, price/grade bands, capacity planning by answer search, numeric bisection.
8 · Interview takeaways
- Say the invariant first. Test n = 0, 1, 2, duplicates, out-of-range targets.
- Look for monotonicity in “minimum X such that …” problems.
- Rotated array: one half is always sorted.
PKnowledge assessment
Attempt everything before opening the answer section.
Conceptual questions
- Binary search on a sorted linked list makes O(log n) comparisons. Why is its running time still O(n)?
- State the invariant of
bisect_left’s loop and explain why it updateshi = midrather thanhi = mid − 1. - Explain why binary search makes at most ⌊log₂ n⌋ + 1 comparisons and why no comparison-based algorithm can guarantee fewer.
- A service only ever asks “is this user ID blocked?”. Would you store blocked IDs in a sorted list with binary search, or a hash set? What changes if it must also answer “how many blocked IDs fall in a numeric range”?
- What property must a predicate have for “binary search on the answer” to be valid? Give a predicate on integers where it fails.
Dry-run exercises
- Run the classic closed-interval search on
[3, 9, 14, 21, 27, 33, 40, 46, 52]for target 46. Givelo, hi, mid, a[mid]for each step and the number of comparisons. - On
a = [1, 1, 3, 3, 3, 7, 9], computebisect_left(a, 3),bisect_right(a, 3),bisect_left(a, 4)andbisect_right(a, 4). Trace the loop forbisect_left(a, 3). - Koko with
piles = [30, 11, 23, 4, 20]andh = 6: tracefirst_true(1, 31, can_finish)and give the answer.
Coding problems
- Range count. Given a sorted list and many queries
(L, R), return how many elements lie in[L, R]in O(log n) per query. - Minimum in a rotated sorted array (LeetCode 153), distinct values, O(log n).
- Smallest divisor given a threshold (LeetCode 1283): smallest positive d with Σ⌈xᵢ/d⌉ ≤ threshold.
Practical engineering scenario
ILLUSTRATIVE An analytics service keeps 50 million event timestamps (64-bit integers) in memory, appended in arrival order, which is almost sorted (events can arrive up to 5 seconds late). Dashboards ask “how many events between time t₁ and t₂?” thousands of times per second. A teammate proposes bisect on the raw list. What goes wrong, and what design would you propose?
Answers
Conceptual answers
- Each probe must reach node
midby following pointers. The walks have lengths about n/2, n/4, … (or worse, restarting from the head), summing to Θ(n). Binary search’s time bound needs O(1) random access. - Invariant: every index < lo holds a value < x, every index ≥ hi holds a value ≥ x. When
a[mid] ≥ x, mid itself satisfies the “≥ x” side and might be the first such index, so it must stay as the new exclusive-boundary candidatehi = mid;mid − 1could skip the answer. Progress holds becausemid < hiwhilelo < hi. - Each comparison leaves at most ⌊m/2⌋ of m candidates, so C(n) = 1 + C(⌊n/2⌋) = number of binary digits of n. Any comparison algorithm is a binary decision tree that needs at least n distinct “found at i” outcomes (plus the gaps), so its height is ≥ ⌈log₂(n+1)⌉ − 1 edges, i.e. some input needs ⌈log₂(n+1)⌉ = ⌊log₂ n⌋ + 1 comparisons. [2]
- Pure membership → hash set: expected O(1), easy updates. Range counting needs order → sorted list with
bisect_right(R) − bisect_left(L)(or a balanced tree if blocks change often). - It must be monotone: once True, True for every larger value. Counter-example: p(t) = (t is even) on integers — F T F T…, so “first True” cannot be found by halving.
Dry-run answers
- (lo 0, hi 8, mid 4, 27 < 46 → lo 5) · (5, 8, mid 6, 40 < 46 → lo 7) · (7, 8, mid 7, 46 = 46 → return 7). 3 comparisons, index 7.
bisect_left(a,3) = 2,bisect_right(a,3) = 5(three 3s),bisect_left(a,4) = bisect_right(a,4) = 5(4 absent; both give the insertion point). Trace ofbisect_left(a, 3): (0, 7, mid 3, a=3 ≥ 3 → hi 3) · (0, 3, mid 1, a=1 < 3 → lo 2) · (2, 3, mid 2, a=3 ≥ 3 → hi 2) · lo = hi = 2.- Hours function H(k) = Σ⌈p/k⌉. (lo 1, hi 31, mid 16, H = 8 > 6 → F, lo 17) · (17, 31, mid 24, H = 6 → T, hi 24) · (17, 24, mid 20, H = 7 → F, lo 21) · (21, 24, mid 22, H = 7 → F, lo 23) · (23, 24, mid 23, H = 6 → T, hi 23). Answer 23, after 5 evaluations instead of up to 30.
Coding answers
from bisect import bisect_left, bisect_right
def range_count(a, L, R): # 1. O(log n) per query
return max(0, bisect_right(a, R) - bisect_left(a, L))
def find_min_rotated(nums: Sequence[int]) -> int:
"""LeetCode 153 — minimum of a rotated sorted array with distinct values."""
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] > nums[hi]:
lo = mid + 1 # minimum is strictly right of mid
else:
hi = mid # mid could be the minimum
return nums[lo]
def smallest_divisor(nums: Sequence[int], threshold: int) -> int:
"""LeetCode 1283 — smallest d with sum(ceil(x / d)) <= threshold."""
return first_true(1, max(nums) + 1,
lambda d: sum((x + d - 1) // d for x in nums) <= threshold)
(2) Compare nums[mid] with nums[hi], not nums[lo]: if nums[mid] > nums[hi] the rotation point (the minimum) is strictly to the right. O(log n). (3) The sum of ceilings never increases as d grows, so the predicate is monotone on [1, max(nums)]; O(n log max). Example: smallest_divisor([1, 2, 5, 9], 6) = 5. All three were tested against brute force in the companion module.
Engineering scenario answer
What goes wrong: the list is not sorted, so bisect may return counts that are silently wrong near late events — the sortedness precondition is violated, and bisect does not check it. [6] Calling insort for each late event would keep it sorted but costs O(n) per insert on a 50-million-element list. [6]
A better design: keep an immutable sorted array of “sealed” events older than, say, 10 seconds (no event can still arrive for that range), plus a small buffer for the most recent window. Every second, sort the buffer’s sealed part (small) and append it — appends to the end keep the big array sorted cheaply. Range queries become bisect_right(t₂) − bisect_left(t₁) on the sealed array (O(log n), about 26 comparisons for 5·107) plus a scan of the small buffer. This is the same “immutable sorted runs + small mutable buffer” idea that LSM-tree storage engines such as LevelDB use, where each sorted block is searched by binary search. [17] If the hot path is in Python, use a typed array (e.g. NumPy’s searchsorted) to avoid per-object comparisons.
QReferences & further reading
- E. Demaine, S. Devadas, “Lecture 7: Linear-Time Sorting,” MIT 6.006 Introduction to Algorithms, Fall 2011, MIT OpenCourseWare. Comparison model; decision trees; searching among n preprocessed items requires Ω(lg n), so binary search is optimal (Sections B, C, G, H).
- E. Demaine, J. Ku, J. Solomon, “Lecture 5: Linear Sorting,” MIT 6.006, Spring 2020, MIT OpenCourseWare. Comparison search lower bound ⌈lg(n+1)⌉ − 1; data-structure table comparing sorted array, direct access array and hash table (find, insert, find_next); comparison sort Ω(n log n) (Sections B, C, G, H, K, P).
- R. Sedgewick, K. Wayne, “3.1 Elementary Symbol Tables,” Algorithms, 4th ed., Princeton University. Binary search in an ordered array; Proposition B (≤ lg N + 1 compares); Proposition C (ordered-array insertion cost); rank (Sections A–D, G, H, J, K).
- R. Sedgewick, K. Wayne,
BinarySearch.java, Algorithms, 4th ed., Princeton University. Reference iterative implementation withmid = lo + (hi − lo) / 2, returning −1 when absent (Sections B, D, F, I). - CP-Algorithms, “Binary search.” Definition; logarithmic step count; lower/upper bound; invariant AL ≤ k < AR; midpoint overflow; arbitrary monotone predicates; search on the answer; continuous search; parallel binary search (Sections A, B, F, G, H, J, M, N).
- Python Software Foundation,
bisect— Array bisection algorithm, Python 3 documentation. bisect_left/right semantics and insertion points; key parameter (3.10+); insort’s O(n) insertion; dict for exact lookups; recipes and grade example (Sections B, C, F, H, I, J, K, L, P). - CPython developers,
Lib/bisect.py, CPython source code (GitHub). Half-open loop with(lo + hi) // 2; ValueError for negative lo; C accelerator_bisect(Sections F, H, I, L). - J. Bloch, “Extra, Extra – Read All About It: Nearly All Binary Searches and Mergesorts are Broken,” Google Research Blog, 2 June 2006. Midpoint overflow bug at ~2³⁰ elements, the Java library bug, the fixes; Bentley’s 1946/1962 remark (Sections B, F, I, L).
- “Binary search,” Wikipedia (secondary survey; summarises Knuth TAOCP Vol. 3 §6.2.1, Bentley’s Programming Pearls, Khuong & Morin and others). History (Babylonian tables, Mauchly 1946, Lehmer 1960, Bottenbruch 1962); Bentley’s ~90 % failure observation; O(1) space; uniform, noisy and cache-aware variants; fractional cascading (Sections B, F, G, H, L, N). Used only where it reports primary sources.
- D. E. Knuth, The Art of Computer Programming, Vol. 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998 (§6.2.1, “Searching an Ordered Table”). Primary source for the history of binary search and for uniform binary search (Sections B, N).
- Topcoder, “Binary Search” (competitive-programming tutorial). The “main theorem”: binary search applies iff the predicate is monotone; designing predicates; search space (Sections B, G, I, K, M).
- J. L. Bentley, A. C.-C. Yao, “An almost optimal algorithm for unbounded searching,” Information Processing Letters 5(3):82–87, 1976. Exponential/unbounded search (Sections J, K, N).
- Y. Perl, A. Itai, H. Avni, “Interpolation search — a log log N search,” Communications of the ACM 21(7):550–553, 1978. Average log log N accesses under uniformly distributed keys (Sections K, N).
- P. E. Black (ed.), “interpolation search,” Dictionary of Algorithms and Data Structures, NIST. O(log log n) average, O(n) worst case; practical caveats versus binary search (Sections K, N).
- P.-V. Khuong, P. Morin, “Array Layouts for Comparison-Based Searching,” ACM Journal of Experimental Algorithmics 22, 2017 (arXiv:1509.05053). Sorted vs Eytzinger vs B-tree vs van Emde Boas layouts; branch-free search and prefetching; cache effects (Sections H, N).
- Git project,
git-bisectdocumentation. Binary search over commit history; good/bad/run commands (Section J). - LevelDB authors (Google),
table/block_builder.cc, LevelDB source code. Restart-point offsets at the end of each block are used to binary search for a key (Sections J, P). - Linux kernel developers,
lib/bsearch.c, Linux kernel source. Generic binary search for sorted in-kernel arrays (Section J). - Oracle,
java.util.Arrays, Java SE 21 API documentation.binarySearchreturns −(insertion point) − 1 when absent (Sections I, J). - cppreference.com,
std::lower_bound. First element not less than value; requires a partitioned range (Sections B, D, I, J). - Python Software Foundation, “Numeric Types — int, float, complex,” Built-in Types. Integers have unlimited precision, so Python midpoints cannot overflow (Sections F, L).
- Python Wiki, “TimeComplexity.” CPython list get-item O(1),
x in listO(n), insert O(n), slicing O(k); set membership O(1) average (Sections B, D, F, H, I, K, L). - C. Lee, J. Zelenski, “Recursion, part 2: Binary Search,” Stanford CS106B lecture slides. Recursive binary search on a sorted vector; logarithmic step count (Section I).
- B. Chazelle, L. J. Guibas, “Fractional cascading: I. A data structuring technique,” Algorithmica 1:133–162, 1986. Searching one key in many sorted lists (Section N).
- T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022 (Ch. 4, the master method). Solving T(n) = T(n/2) + Θ(1) = Θ(lg n) (Section G).
- Python Software Foundation,
sys.getrecursionlimit, Python 3 documentation. Recursion depth limit relevant to the recursive implementation (Section H). - T. Peters,
Objects/listsort.txt, CPython source (Timsort design notes). Timsort exploits existing order; as few as n − 1 comparisons on sorted input (Section H).
Interactive practice: VisuAlgo (sorting, the prerequisite for binary search) and the LeetCode problems linked in Sections M and P.