AlgorithmAlgorithmA precise, step-by-step procedure that solves a specific problem, with provable correctness and cost.e.g. Binary search, merge sort, Dijkstra
DSA Learning Studio · Chapter 06 · Searching

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.

Difficulty: Beginner → Intermediate (advanced section: Upper-intermediate) Reading time: ~85 minutes (+ 30 min exercises) Language: Python 3.10+ 6 interactive labs

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:

  1. Explain why binary search needs sorted data and random access, and why it makes at most ⌊log₂ n⌋ + 1 comparisons.
  2. Write a correct binary search from memory by stating its loop invariant first, and prove it terminates.
  3. Choose between the closed-interval [lo, hi] and half-open [lo, hi) templates and avoid the classic off-by-one and infinite-loop bugs.
  4. Use lower bound and upper bound (Python’s bisect_left / bisect_right) to find first/last occurrences, counts, insertion points and predecessors.
  5. Recognise “binary search on the answer”: turn an optimisation problem into a monotone yes/no predicate and search over the answer space.
  6. 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.
The one-sentence promise If your data is sorted and you can jump to any position, one comparison with the middle element rules out half of what remains — so a million items need at most 20 comparisons, and a billion at most 30. [3][5]
How the visuals in this chapter are made This environment has no image-generation model, so every “whiteboard” illustration is drawn in code: a small sketch renderer turns the actual data of each example into hand-drawn-style SVG strokes with handwriting labels, so every number in a figure is exact. All six interactive labs are fully working. Figures follow the colour language below; examples and analogies written by the author (not taken from a source) are marked ILLUSTRATIVE.

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]

Formal definition Let A[0..n−1] be sorted in non-decreasing order and let x be a key. Binary search maintains an interval of indices that must contain x if x occurs in A. At each step it probes the middle index m of the interval, compares A[m] with x, and either stops (A[m] = x) or replaces the interval with the half on the correct side of m. It reports “not found” when the interval becomes empty. In the worst case it uses at most ⌊lg n⌋ + 1 comparisons. [3][4]
Simple English definition Binary search is the “higher or lower?” guessing game played perfectly: always guess the middle of what is still possible, and every answer crosses out half the possibilities.

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

  1. 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]
  2. 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]
  3. Halving gives logarithms. An interval of size n can be halved only about log₂ n times before it is empty. [5]
  4. 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]
  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

TermMeaning
Search intervalThe indices that might still hold the answer, written [lo, hi] (both ends included) or [lo, hi) (hi excluded).
Probe / midThe index compared in this step, normally (lo + hi) // 2.
InvariantA statement about lo, hi that is true before and after every loop iteration.
Lower boundThe 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 boundThe first index i with A[i] > x (= bisect_right). [6][20]
Monotone predicateA 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

ComponentSpecification
InputA sequence A of n comparable keys, sorted in non-decreasing order, supporting O(1) access by index; and a query key x.
OutputAn 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.
ConstraintsMany queries against the same data; n may be millions or billions; we want far fewer than n comparisons per query.
ModelKeys 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]

Real-world analogy: the dictionary on your desk ILLUSTRATIVE To find “otter” in a 1 000-page paper dictionary you do not read from page 1. You open near the middle, see “mango”, and know “otter” is in the right half — 500 pages gone in one look. Open the middle of that half, and so on. About ten looks find the page, because 210 = 1024. The method only works because the words are alphabetised (sorted) and you can flip straight to any page (random access). Shuffle the pages, or glue them into a scroll, and you are back to reading from the start.

DVisual whiteboard explanations

All diagrams in this chapter use one colour language:

Blue — original data, the live search interval Green — found element, answers, the half we keep Red — discarded half, failed comparisons, bugs Yellow/orange — mid, the element being compared Purple — pointers, relationships, recursion Black — labels and definitions
Figure D.1 · Concept introductionEvery answer crosses out half
still possibleruled outthe guess (middle)found
ILLUSTRATIVE
  1. Secret number 37, range 1–100. Guess the middle, 50: “too high” → everything from 50 to 100 is crossed out.
  2. Range 1–49, guess 25: “too low” → 1 to 25 crossed out.
  3. Range 26–49, guess the middle, 37: found in 3 guesses. No secret in 1–100 needs more than 7, because 27 = 128 ≥ 100.
Technical interpretation: each comparison partitions the candidates into “left of mid”, “mid” and “right of mid”; keeping only one side halves the problem, giving ⌊log₂ n⌋ + 1 comparisons in the worst case. [3][5]
Figure D.2 · Memory representationWhy binary search needs random access
sorted array slotmiddle elementaddress arithmetic / next pointerswalk needed to reach the middle
  1. Top: a sorted array of 10 integers stored contiguously from (illustrative) base address 2000, 8 bytes per slot.
  2. The middle index is (0 + 9) // 2 = 4, and its address is computed directly: 2000 + 4 × 8 = 2032. One step.
  3. Bottom: the same keys in a linked list. To reach the 5th node you must follow 4 next pointers; every probe of a binary search would cost a walk.
Technical interpretation: binary search makes O(log n) comparisons on any structure, but its O(log n) time needs O(1) indexing. Python lists give O(1) a[i]; linked structures do not. [22][3]
Figure D.3 · Step-by-step executionSuccessful search for 23
live interval [lo, hi]middiscardedfoundlo / hi pointers
  1. Step 1: lo = 0, hi = 9, mid = 4, A[4] = 16 < 23 → the answer must be right of 4: lo = 5.
  2. Step 2: lo = 5, hi = 9, mid = 7, A[7] = 56 > 23 → answer left of 7: hi = 6.
  3. Step 3: lo = 5, hi = 6, mid = 5, A[5] = 23 = target → return 5. Three comparisons for ten elements.
Technical interpretation: the interval sizes go 10 → 5 → 2; each update moves a bound past mid (mid ± 1) because mid itself has been ruled out — that is what guarantees progress. These are the exact rows printed by the instrumented code in Section I. [4]
Figure D.4 · Before and afterUnsuccessful search: the pointers cross
arrayprobes, in orderempty interval: not foundinsertion point (lo)
  1. Searching for 40 probes indices 4 (16), 7 (56), 5 (23) and 6 (38).
  2. After the last probe lo = 7 and hi = 6: the interval [7, 6] is empty, so 40 is absent.
  3. Bonus: lo = 7 is exactly where 40 would have to be inserted to keep the array sorted — between 38 and 56.
Technical interpretation: when the closed-interval loop ends, every index < lo holds a value < x and every index > hi holds a value > x, so lo is the insertion point — the same number bisect_left returns. [6][3]
Figure D.5 · Internal workingDuplicates: lower bound, upper bound, count
arraypredicate Falsepredicate True / boundaryrange of equal keys
  1. 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.
  2. Ask “is A[i] > 2?”: F F F F T T T. The first True is index 4 → upper bound.
  3. The copies of 2 occupy [1, 4), so the count is 4 − 1 = 3.
Technical interpretation: both bounds are “find the first True of a monotone predicate” — the same loop with < or ≤. Python names them bisect_left and bisect_right; C++ names them lower_bound and upper_bound. [6][20][5]
Figure D.6 · Time complexity visualizationA million items, twenty halvings
remaining interval size (log scale bar)step numberdonelinear search, for scale
  1. Start with n = 1 000 000 candidates. After each comparison at most ⌊size/2⌋ remain (the half on one side of mid).
  2. Sizes: 1 000 000 → 500 000 → 250 000 → … → 1 after 19 halvings; the 20th comparison checks the last candidate.
  3. Linear search may need all 1 000 000 comparisons for the same answer.
Technical interpretation: the number of comparisons is ⌊log₂ n⌋ + 1 = 20 for n = 10⁶ (and 30 for 10⁹); the companion code confirms 20 as the maximum over 2 000 random targets. [3][5]

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.

Lab 1 · Core visualizerWatch lo, mid and hi close in
in intervalmiddiscardedanswerlomidhi
Lab 2 · You are the algorithmHigher-or-lower: can you beat ⌈log₂(N+1)⌉?
11000
Lab 3 · Lower bound, visuallyThe decision tree of binary search
Array is A[i] = 10·(i+1). Circles are comparisons with A[mid] (left edge “<”, right edge “>”); squares are the n + 1 possible “not found” gaps.
Lab 4 · Binary search on the answerKoko eating bananas: find the slowest speed that still works
Answer space — speeds k = 1 … max(piles). Predicate can_finish(k): hours(k) ≤ h. Cells stay grey until binary search actually evaluates them.
Lab 5 · VariationSearch in a rotated sorted array
Lab 6 · Bug hunterRun broken binary searches and watch them fail

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

Figure F.1 · Execution flowThe classic loop as a flowchart
stepcompute / compare midreturn indexreturn −1loop back
  1. Initialise lo = 0, hi = n − 1.
  2. If lo > hi, the interval is empty: return −1.
  3. Compute mid and compare A[mid] with the target: equal → return mid; smaller → lo = mid + 1; larger → hi = mid − 1; loop.
Technical interpretation: every path around the loop shrinks 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]:

  1. Set the interval to the whole array: lo = 0, hi = n − 1.
  2. While the interval is non-empty (lo ≤ hi), compute mid = lo + (hi − lo) // 2.
  3. Compare once. If A[mid] == x you are done.
  4. If A[mid] < x, then A[lo..mid] are all < x: discard them with lo = mid + 1.
  5. Otherwise A[mid..hi] are all > x: discard them with hi = mid − 1.
  6. If the loop exits, the interval is empty and x is absent; lo is 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]

Closed [lo, hi] — “find x” lo, hi = 0, n − 1
while lo <= hi:
  lo = mid + 1 or hi = mid − 1
Invariant: if x is present, its index is in [lo, hi]. Empty when lo = hi + 1. Natural when you can stop on equality.
Half-open [lo, hi) — “find a boundary” lo, hi = 0, n
while lo < hi:
  lo = mid + 1 or hi = mid
Invariant: 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

SituationWhat happens in the classic loopResult
Empty array (n = 0)hi = −1 < lo = 0; the loop body never runs.−1, zero comparisons
One elementOne probe at index 0.0 or −1
Target smaller than every elementhi keeps moving left until hi = −1.−1; insertion point lo = 0
Target larger than every elementlo keeps moving right until lo = n.−1; insertion point n
DuplicatesStops 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 inputThe 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

Invariant (closed template) I: for every index i < lo, A[i] < x; and for every index i > hi, A[i] > x. Equivalently: if x occurs in A, it occurs in A[lo..hi]. [5]
  1. Initialisation. With lo = 0, hi = n−1 there are no indices < lo or > hi, so I holds vacuously.
  2. 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.
  3. 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.
  4. 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

C(0) = 0,    C(n) = 1 + C(⌊n/2⌋)   ⟹   C(n) = ⌊log₂ n⌋ + 1 for n ≥ 1

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

Figure G.1 · Mathematical structureBinary search on 7 keys is a balanced decision tree
comparison node (index: value)< / > branches“not found” leaves (gaps)a root-to-leaf path = one run
  1. Each circle is a comparison of x with A[mid]; its two children are what happens next on “<” or “>”.
  2. A search ends at a circle (found) or at one of the n + 1 = 8 squares (absent, falling in a gap between keys).
  3. The green path is a search for 35: compare with 40, then 20, then 30, then fall into the gap (30, 40).
Technical interpretation: any comparison-based search algorithm can be drawn as such a binary tree with at least n internal nodes; a binary tree with n internal nodes has height ≥ ⌈lg(n+1)⌉ − 1 (measured in edges), so some input needs ⌈lg(n+1)⌉ comparisons — exactly binary search’s ⌊lg n⌋ + 1. [2][1]

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

average = (1/n) · Σd=1..k d · 2d−1 = ((k − 1)·2k + 1) / n  ≈  log₂ n − 1

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

The “main theorem” of binary search Let p be a predicate on an ordered search space S. Binary search can find the smallest t with p(t) true if and only if p is monotone: p(t) implies p(u) for every u > t. [11]

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]

OperationBest caseAverage caseWorst caseAuxiliary 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_left never 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.insert shifts 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]
Amortized analysis — where it does and does not apply A single search has no amortized component. Amortization appears only in the surrounding structure: if you append keys that arrive in increasing order, 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

  • bisect runs in C (the _bisect accelerator), 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

LineWhy it is there
lo, hi = 0, len(a) - 1Closed interval covering the whole list. For an empty list hi = −1, so the loop is skipped.
while lo <= hiThe 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) // 2Middle 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] == targetEarly exit — the source of the Θ(1) best case.
lo = mid + 1 / hi = mid - 1Discard mid and its whole side. The ±1 guarantees progress; without it the loop can stall (Lab 6, Bug B).
return -1Interval 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.lohimida[mid]CompareAction
10941616 < 23lo = 5
25975656 > 23hi = 6
356523equalreturn 5

Same array, target 40 (absent)

Iter.lohimida[mid]CompareAction
10941616 < 40lo = 5
25975656 > 40hi = 6
35652323 < 40lo = 6
46663838 < 40lo = 7
—76lo > hi: interval emptyreturn −1 (insertion point 7)

lower_bound([1, 2, 2, 2, 3, 5, 8], 2)

Iter.lohimida[mid]TestAction
10732a[mid] ≥ 2hi = 3
20312a[mid] ≥ 2hi = 1
30101a[mid] < 2lo = 1
—11lo == hireturn 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’s bisect likewise trusts the caller. [6]
  • Non-indexable input (a set, a generator) raises TypeError: binary search needs random access.
  • Mixed types (e.g. [1, "a"]) raise TypeError from < in Python 3 — a feature, not a bug.
  • Floating-point keys: NaN compares 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

ImplementationReturnsTimeExtra spaceUse when
Iterative closed (binary_search)some index of x, or −1O(log n)O(1)Distinct keys, membership + position.
Recursive (binary_search_rec)sameO(log n)O(log n)Teaching; divide-and-conquer style code.
lower_bound / upper_boundboundary index 0…nO(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 predBinary search on the answer.
bisect moduleboundary indexO(log n)O(1)Production Python: C speed, tested. [7]
x in lst / lst.index(x)bool / first indexO(n)O(1)Unsorted or tiny lists. [22]
x in set_boolO(1) avgO(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.

Figure J.1 · Real-world applicationgit bisect: binary search over history
good (no bug)bad (bug present)commit being testeduntested commitfirst bad commit
ILLUSTRATIVE HISTORY
  1. 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.
  2. 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.
  3. Answer: c6 is the first bad commit, found with 4 tests instead of up to 16.
Technical interpretation: the documentation of 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]
DomainHow binary search is used
Developer toolinggit bisect finds the first bad commit between a known-good and a known-bad revision by testing midpoints. [16]
Databases & storage enginesLevelDB 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 systemsThe Linux kernel ships a generic bsearch() in lib/bsearch.c for sorted in-kernel arrays, parameterised by element size and comparison function. [18]
Language runtimesPython’s bisect, Java’s Arrays.binarySearch, and C++’s lower_bound/upper_bound/equal_range are standard-library binary searches. [6][19][20]
Backend engineeringTiered 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).
NetworkingILLUSTRATIVE 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 systemsILLUSTRATIVE 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 enginesILLUSTRATIVE 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 planningBisection 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

MethodRequiresSearchInsertOrdered queries?Extra space
Linear searchnothingO(n)O(1) appendby full scanO(1)
Binary search on sorted arraysorted, random accessΘ(log n)O(n)yes, O(log n)O(1)
Hash set / dicthashable keysO(1) expectedO(1) expected amortizednoO(n)
Balanced BSTcomparable keysO(log n)O(log n)yesO(n) pointers
Interpolation searchsorted numeric, near-uniform keysO(log log n) avg, O(n) worstO(n)yesO(1)
Exponential (galloping) searchsorted, maybe unboundedO(log i), i = answer positionO(n)yesO(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].

Figure K.1 · Comparison with alternativesWhich search should I use?
questionrecommended choiceyes / no branch
  1. Only exact membership, no order needed → a hash set wins (expected O(1)).
  2. Need predecessor/successor/range queries on mostly static data → sort once and binary search.
  3. Need ordered queries and frequent inserts/deletes → a balanced BST (or a B-tree in storage).
  4. Tiny or one-off unsorted data → just scan; sorting costs more than it saves.
Technical interpretation: the choice is about which operations dominate — MIT 6.006 summarises it as a table of build/find/insert/find_next costs for each structure. [2]

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/set is 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)

✘ Wrong
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 -1
✔ Right
lo, hi = 0, len(a) - 1      # closed interval
while lo <= hi:              # non-empty while lo <= hi
    ...
return -1

2. Not making progress: lo = mid (Bug B)

✘ Wrong
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 - 1
✔ Right (“last index with a[i] ≤ x”)
while 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) - 1

Rule: 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)

✘ Wrong (Java/C/C++)
int mid = (low + high) / 2;  // low + high may exceed 2^31 - 1
✔ Right
int mid = low + (high - low) / 2;
int mid = (low + high) >>> 1;   // Java unsigned shift

Bloch 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

✘ Wrong
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
✔ Right
# 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

✘ Risky
while hi - lo > 1e-12:      # may spin forever when
    mid = (lo + hi) / 2     # lo and hi are adjacent floats
    ...
✔ Robust
for _ in range(100):        # 2**-100 shrink: plenty
    mid = (lo + hi) / 2
    ...

11. Interview mistakes

  • Coding before saying what lo and hi mean. 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 bisect exists — interviewers usually accept it once you can explain it.

MInterview preparation

M.1 The six binary-search patterns

PatternSignal in the problemCore moveTypical problems
Exact searchsorted array, “return the index”closed template, stop on equality704 Binary Search
Boundary“first / last / insert position / how many”bisect_left, bisect_right35, 34, 278 First Bad Version
Answer space“minimum capacity / speed / largest minimum…”, plus a cheap feasibility checkfirst_true over candidate answers875, 1011, 410, 1283
Partially sorted“rotated”, “mountain”, “bitonic”decide which half is sorted / which way is uphill33, 153, 162
Implicit array2-D sorted matrix, integer square rootmap index ↔ value with arithmetic74, 69
Partition search“median / k-th of two sorted arrays”binary search a cut position, check cross inequalities4

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.

HintClosed 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.

HintBoth cases are the same number: the first index with nums[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).

HintTwo 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.

HintAt 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.

HintHours 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).

HintIf nums[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 1Choose how many elements i the left half takes from the shorter array A; then j = half − i come from B.
Hint 2The 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.

HintGuess 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.

Interview script that works (1) Say what is monotone. (2) Say what 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.

Level
Difficulty
0 / 38 solved
Saved in this browser

Basic8 problems

Direct applications of this chapter’s core idea.

Binary Search

Halve a sorted search space; lower and upper bounds; rotated arrays.

  1. Binary Search⤢EASYLeetCode
  2. Search Insert Position⤢EASYLeetCode
  3. First Bad Version⤢EASYLeetCode
  4. Sqrt(x)⤢EASYLeetCode
  5. Floor in a Sorted Array⤢EASYGeeksforGeeks
  6. Ceil in a Sorted Array⤢EASYGeeksforGeeks
  7. Implement Lower Bound⤢EASYGeeksforGeeks
  8. Implement Upper Bound⤢EASYGeeksforGeeks

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.

  1. Search in Rotated Sorted Array⤢MEDIUMLeetCode
  2. Find Peak Element⤢MEDIUMLeetCode
  3. Search a 2D Matrix⤢MEDIUMLeetCode

Binary Search on Answers

Search over the answer itself using a monotone yes/no check.

  1. Minimum Time to Complete Trips⤢MEDIUMLeetCode
  2. Koko Eating Bananas⤢MEDIUMLeetCode
  3. Minimum Speed to Arrive on Time⤢MEDIUMLeetCode
  4. Wood Cutting Made Easy⤢MEDIUMInterviewBit

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.

  1. Find in Mountain Array⤢HARDLeetCode
  2. Median of Two Sorted Arrays⤢HARDLeetCode

Binary Search on Answers

Search over the answer itself using a monotone yes/no check.

  1. Aggressive Cows⤢HARDGeeksforGeeks
  2. Split Array Largest Sum⤢HARDLeetCode
  3. Allocate Minimum Number of Pages⤢HARDGeeksforGeeks
  4. The Painter's Partition Problem-II⤢HARDGeeksforGeeks
  5. Red Zone⤢HARDInterviewBit
  6. Maximum Average Subarray II⤢HARDLeetCode

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.

Binary Search
Sorted + random access → compare with the middle → throw away half
What is 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.

mid = lo + (hi − lo) // 2

Needs: sorted order + O(1) indexing (array, not linked list).

The invariant

“If x is in A, it is inside [lo, hi].”

A[mid] < x → lo = mid + 1
A[mid] > x → hi = mid − 1

Loop while lo ≤ hi. Exit ⇒ absent, and lo = insertion point.

Traps
  • 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)
Example: find 23

3 comparisons for 10 items → index 5

Boundaries (duplicates)
bisect_left = first a[i] ≥ x
bisect_right = first a[i] > x

count(x) = right − left · last = right − 1

★ Key Takeaway

Binary search finds the boundary where a monotone yes/no question flips: F F F T T T.

Cost
bestO(1)
avg / worstO(log n)
space (loop)O(1)
insortO(n)
Why log n?

n → n/2 → n/4 → … → 1
⌊log₂ n⌋ + 1 compares
10⁶ → 20 · 10⁹ → 30

Python

from bisect import bisect_left, bisect_right, insort

key= since 3.10

Uses
  • 🔍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] == x
  • insort(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

  1. Binary search on a sorted linked list makes O(log n) comparisons. Why is its running time still O(n)?
  2. State the invariant of bisect_left’s loop and explain why it updates hi = mid rather than hi = mid − 1.
  3. Explain why binary search makes at most ⌊log₂ n⌋ + 1 comparisons and why no comparison-based algorithm can guarantee fewer.
  4. 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”?
  5. 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

  1. Run the classic closed-interval search on [3, 9, 14, 21, 27, 33, 40, 46, 52] for target 46. Give lo, hi, mid, a[mid] for each step and the number of comparisons.
  2. On a = [1, 1, 3, 3, 3, 7, 9], compute bisect_left(a, 3), bisect_right(a, 3), bisect_left(a, 4) and bisect_right(a, 4). Trace the loop for bisect_left(a, 3).
  3. Koko with piles = [30, 11, 23, 4, 20] and h = 6: trace first_true(1, 31, can_finish) and give the answer.

Coding problems

  1. 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.
  2. Minimum in a rotated sorted array (LeetCode 153), distinct values, O(log n).
  3. 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
  1. Each probe must reach node mid by 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.
  2. 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 candidate hi = mid; mid − 1 could skip the answer. Progress holds because mid < hi while lo < hi.
  3. 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]
  4. 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).
  5. 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
  1. (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.
  2. 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 of bisect_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.
  3. 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

  1. 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).
  2. 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).
  3. 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).
  4. R. Sedgewick, K. Wayne, BinarySearch.java, Algorithms, 4th ed., Princeton University. Reference iterative implementation with mid = lo + (hi − lo) / 2, returning −1 when absent (Sections B, D, F, I).
  5. 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).
  6. 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).
  7. 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).
  8. 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).
  9. “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.
  10. 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).
  11. 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).
  12. 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).
  13. 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).
  14. 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).
  15. 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).
  16. Git project, git-bisect documentation. Binary search over commit history; good/bad/run commands (Section J).
  17. 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).
  18. Linux kernel developers, lib/bsearch.c, Linux kernel source. Generic binary search for sorted in-kernel arrays (Section J).
  19. Oracle, java.util.Arrays, Java SE 21 API documentation. binarySearch returns −(insertion point) − 1 when absent (Sections I, J).
  20. cppreference.com, std::lower_bound. First element not less than value; requires a partitioned range (Sections B, D, I, J).
  21. Python Software Foundation, “Numeric Types — int, float, complex,” Built-in Types. Integers have unlimited precision, so Python midpoints cannot overflow (Sections F, L).
  22. Python Wiki, “TimeComplexity.” CPython list get-item O(1), x in list O(n), insert O(n), slicing O(k); set membership O(1) average (Sections B, D, F, H, I, K, L).
  23. 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).
  24. 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).
  25. 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).
  26. Python Software Foundation, sys.getrecursionlimit, Python 3 documentation. Recursion depth limit relevant to the recursive implementation (Section H).
  27. 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.