Practice Discrete Math

Algorithms / Binary Search Invariants

Least You Need to Know: Binary Search Invariants and Boundary Updates

Binary search works because the search interval maintains an **invariant**: the desired answer is still inside the remaining range. Each comparison must eliminate only the half that is provably impossible, and the boundary update must match the exact question being asked.

The least you need to know

Key notation

lo, hi current candidate range
mid middle index or middle candidate
invariant property that remains true after each update

Tiny worked example

  • Suppose you want the first index whose value is at least `x`.
  • Keep the invariant that the answer is somewhere in `[lo, hi]`.
  • If `a[mid]` is already at least `x`, keep the left half by setting `hi = mid`.
  • Otherwise eliminate `mid` and the entire left half by setting `lo = mid + 1`.

Common mistakes

How to recognize this kind of problem

Start practice