Skip to the workspace
Pebellslearn by building
Binary Search  ›  Lesson

Halving the Search: Classic Binary Search

Binary Search 12 minIn a sorted list, checking the middle item tells you which half cannot contain the target, so each comparison halves the search and a million items need only about twenty checks.

leetcode / Halving the Search: Classic Binary Search

Explore each scene at your own pace.

01 · The rule

The rule

Halving the Search: Classic Binary Search

A raffle has sold a million tickets, and their numbers are stored in sorted order. Someone asks whether ticket 730,512 was sold. Reading the list from the start could take a million checks. Opening it in the middle, seeing which half the number must be in, and repeating takes about twenty.

The rule

Sorted? Check the middle and throw away the half that cannot hold it.

Keep two bounds, lo and hi, around the part of the list that could still contain the target. Look at the middle item. If it is the target, you are done. If it is too small, the target can only be to its right; if too big, only to its left. Either way, half the remaining list is gone after one comparison.

def find(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:                 # the window still holds at least one item
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1            # target can only be right of mid
        else:
            hi = mid - 1            # target can only be left of mid
    return -1

The idea that keeps this correct is an invariant, a promise that is true before every loop: if the target is in the list at all, it lies between lo and hi. Every update keeps the promise, and when lo passes hi the window is empty, so the target is not there. The + 1 and - 1 matter too: mid has already been checked, so it leaves the window.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.