Binary Search · Lesson

Binary search, explained: the idea, the template and every pattern

Learn binary search from scratch: the one idea, a bug-free template in Java, Python, C++ and JavaScript, and 8 interview patterns with practice problems.

8 patterns · 52 problems · Java, Python, C++ and JavaScript

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

What binary search does

Binary search finds something in a sorted search space by checking the middle and throwing away the half that cannot hold the answer. Every check halves what is left, so n items need about log₂ n checks: a million items in 20 steps, a billion in 30.

A linear scan looks at every item. Binary search uses the order to skip almost all of them. That is the whole trick, and it is why interviewers reach for it whenever an O(n) solution is "too slow".

The one idea behind every variation

You do not really need a sorted array. You need a monotonic condition: a yes/no check ok(x) that is no, no, no, … yes, yes, yes across the search space. Binary search finds where the answers flip.

A sorted array gives you ok(i) = a[i] >= target. A rotated array, "the first bad version", "the slowest speed that still finishes in time" and "the largest distance that still fits" are the same loop with a different ok. Learn to write ok and every pattern below becomes familiar.

The invariant that keeps it bug-free

Almost every binary search bug is an off-by-one or an infinite loop. Both go away if you decide what lo and hi mean and keep that true on every step:

  • Exact search: the answer, if it exists, is in [lo, hi] (both ends included). Loop while lo <= hi and move to mid + 1 or mid - 1.
  • Boundary search: the answer is in [lo, hi) or is hi itself. Loop while lo < hi, set hi = mid when ok(mid), else lo = mid + 1.

Compute mid = lo + (hi - lo) / 2 so lo + hi never overflows, and check that every branch makes the range smaller. If a branch sets lo = mid, round mid up, or a two-element range never shrinks.

What it costs

OperationTimeSpace
Find a value in a sorted arrayO(log n)O(1)
First or last position (lower / upper bound)O(log n)O(1)
Search a sorted m × n matrixO(log(m·n)) or O(m + n)O(1)
Search on the answer, range R, O(n) checkO(n log R)O(1)
Sort first, if the input is not sortedO(n log n)depends

Built into your language

Library calls
int[] a = {1, 3, 3, 5, 8};
Arrays.binarySearch(a, 5);      // 3 (index); a negative value when missing

// floor / ceiling on a sorted set or map
TreeSet<Integer> set = new TreeSet<>(List.of(1, 3, 5, 8));
set.floor(4);                   // 3: largest value <= 4
set.ceiling(4);                 // 5: smallest value >= 4
set.higher(5);                  // 8: smallest value > 5

Mistakes everyone makes

  • Writing (lo + hi) / 2 in Java or C++ with values near 2³¹: it overflows. Use lo + (hi - lo) / 2.
  • Mixing while (lo <= hi) with hi = mid: the loop can run forever when lo == hi.
  • Setting lo = mid with mid rounded down: a range of two never shrinks. Round up instead.
  • Searching an unsorted array. Sort first, or check that the condition really is monotonic.
  • Returning lo without checking it: if no element satisfies the condition, lo lands one past the end.

The 8 patterns, in order

Each one: the idea and template, its variations with a worked example, then problems for you to solve.

  1. 1 Exact search and binary search inside a design Find an exact value in a sorted array, then use the same loop inside data structures that are sorted by time or by running sum. 2 variations · 5 problems
  2. 2 Lower bound, upper bound, floor and ceiling Find where a value would go: the first element ≥ x (lower bound) or > x (upper bound). Floor, ceiling, first and last position and counts all come from these two. 5 variations · 12 problems
  3. 3 Binary search on a condition: first true No target value at all: binary search the first index where a yes/no condition becomes true. A bad version, an index-parity break or a downhill slope. 3 variations · 3 problems
  4. 4 Rotated sorted arrays A sorted array cut and swapped. At every mid, one half is still sorted: find out which, then decide whether the answer can be in it. 3 variations · 5 problems
  5. 5 Searching a sorted 2D matrix Two shapes. A matrix sorted row after row is one long sorted array: binary search the flattened index. A matrix sorted by row and by column is searched by stepping from a corner. 2 variations · 4 problems
  6. 6 Binary search over numbers: roots, powers, unbounded ranges The search space is a range of numbers, not an array. Square roots and nth roots: the largest x with x² ≤ n. Plus two cousins: halving the exponent and galloping into an unbounded array. 3 variations · 4 problems
  7. 7 Binary search on the answer The most important pattern for interviews. You cannot find the answer directly, but you can check a guess. If "k works" means every bigger (or smaller) k also works, binary search the guess. 5 variations · 18 problems
  8. 8 Binary search on a partition Split two sorted arrays so the left parts hold exactly half the elements and everything on the left is ≤ everything on the right. Binary search where to cut the shorter array. 1 variation · 1 problem