awelgorithms

// learn

Binary search, from exact match to search on the answer

Binary search finds a target in sorted data by halving the range on every step: compare with the middle, keep the half that can still hold the answer, throw the other half away. A million items take about 20 comparisons.

Updated

The idea is bigger than sorted arrays. Binary search works on any yes/no question that flips once: false, false, false, then true, true. Find the first true, and you can answer "first index not less than x", "smallest speed that finishes in time" or "peak of a mountain array" with the same loop.

When to use it

The template

def first_true(lo, hi, ok):     # ok() flips once: False...False True...True
    while lo < hi:
        mid = (lo + hi) // 2        # lower middle, so hi = mid always shrinks
        if ok(mid):
            hi = mid                # mid works: the answer is mid or earlier
        else:
            lo = mid + 1            # mid fails: the answer is after it
    return lo                       # first value where ok() is True

# lower bound: first index i with nums[i] >= x
# first_true(0, len(nums), lambda i: nums[i] >= x)

The variants you will meet

Exact match

The textbook version: keep [lo, hi], compare the middle with the target, return when equal. It only works when the data is sorted by the thing you compare.

Lower and upper bounds

The first index not less than x, and the first index greater than x. Together they give the range of x and its count, and they are what bisect_left and bisect_right return.

Search on the answer

When the answer is a number and "does x work?" flips once as x grows, binary search the answer itself: Koko eating bananas, shipping within D days, splitting an array to minimise the largest sum.

Rotated, unbounded and peaks

A rotated sorted array still has one sorted half at every middle, so you can tell which half to keep. Unknown lengths are handled by doubling until you overshoot; peaks by following the rising side.

Matrices

A matrix whose rows continue each other is one sorted list of m·n items. A matrix sorted by rows and by columns is better searched from a corner, one row or column per step.

Real numbers

For square roots and other real answers, loop a fixed number of times or until the range is smaller than the precision you need, and prefer integer searches when the answer is an integer.

Time and space complexity

O(log n) comparisons, because each step halves the range: 2^20 is about a million, so 20 steps cover it. Search on the answer costs O(log R) checks over a range of size R, times the cost of one check. Extra space is O(1) for the loop.

check which skills you have 10 minutes, free, no account.

All 16 lessons, in order

Common questions

Why does binary search need sorted data?

Throwing away half the range is only safe if everything in that half is known to be on the wrong side of the target. Sorting guarantees it. More generally, any check that is false and then true (monotonic) gives the same guarantee.

Should I use lo <= hi or lo < hi?

Use lo <= hi with hi = mid - 1 when you return as soon as you find an exact match. Use lo < hi with hi = mid when you are looking for a boundary such as the first true; the loop ends with lo == hi on the answer. Mixing the two causes most infinite loops.

How do I avoid integer overflow in mid?

In Java, C++ and similar languages write mid = lo + (hi - lo) / 2, because lo + hi can exceed the integer range. Python integers don't overflow, so (lo + hi) // 2 is fine there.

What is search on the answer?

Instead of searching an array, you binary search the answer's range. If speed s finishes the job in time, any faster speed does too, so "does s work?" flips once and the smallest working s can be found in O(log range) checks.

Other guides