Searching and lookup · Intermediate

Binary search on a monotonic predicate

When a yes/no question flips exactly once over a range, binary search finds the boundary in O(log range) checks, whether the range is indices or answers.

On this page
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

The idea

Binary search does not need an array. It needs a predicate ok(x) that is false, false, …, false, true, true, … over an ordered range. Halving the range while keeping one false end and one true end finds the first true in about log₂(range) evaluations.

On a sorted array the predicate is "a[i] ≥ target" (lower bound) or "a[i] > target" (upper bound). On an answer space it is "can the job be done with capacity x?": if it works for x it works for every larger x, so the smallest feasible x is a boundary.

How to recognise it

  • Sorted input, and you need the first or last position of something, or where it would be inserted.
  • The question asks for the minimum (or maximum) value such that a condition holds, and the condition is monotonic in that value.
  • A feasibility check is easy to write, but computing the optimum directly is not.
  • Constraints allow O(n log V) where V is the size of the value range.

When not to use it

  • The predicate is not monotonic (it flips more than once); binary search will return some flip, not the one you want.
  • The data is unsorted and you search only once: a linear scan is O(n), cheaper than sorting first.

Template

Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.

# First x in [lo, hi] with ok(x) true; returns hi + 1 if none
# Invariant: ok is false for everything < lo, true for everything > hi
while lo <= hi:
    mid = lo + (hi - lo) // 2      # avoids overflow of lo + hi
    if ok(mid):
        hi = mid - 1               # mid might be the answer; look left
    else:
        lo = mid + 1
return lo

# Lower bound in a sorted array: ok(i) = a[i] >= target, over [0, n - 1]
  • State the invariant before writing the loop; the update rules and the return value follow from it.
  • For real-valued answers, loop a fixed number of times instead of comparing floats for equality.

Complexity

Time O(log R × cost of ok), extra space O(1). R is the size of the searched range. On an array ok is O(1), giving O(log n); on an answer space ok often scans the input, giving O(n log R).

Worked examples

First broken build among versions 1..8

Suppose builds 1–5 pass and 6–8 fail, so ok(v) = "v is broken". mid = 4 passes, lo = 5. mid = 6 fails, hi = 5. mid = 5 passes, lo = 6 > hi. The answer is 6 after three checks.

Pitfalls

  • `(lo + hi) / 2` overflowing in fixed-width integers.
  • Mixing inclusive and exclusive bounds, which causes infinite loops when lo and hi are adjacent.
  • Returning mid from inside the loop when the task asks for the first occurrence.

Practise it

Solved problems with hints, a correctness argument and four tested implementations:

Learn the foundations

Related patterns

References

dsa.pattern.binary-search-on-answer · version 1