0:00 / 0:00

Find a target in a sorted list. Check the middle and throw away the half that can't hold it, so each step halves the search.

▼

The problem

Given a list of numbers sorted in ascending order and a target, return the target's index, or -1 if it isn't in the list.

Example: nums = [3, 8, 12, 17, 23, 29, 35, 41, 50, 64, 72, 80, 86, 91, 97].

TRY IT ON LEETCODE ▶

The solution

def search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Transcript

Binary Search. You get a sorted list of numbers and a target. Return the target's index, or minus one if it isn't there.

Here are fifteen numbers, and the target is seventy-two. The simple way checks them one by one from the left. Seventy-two is eleventh, so that's eleven checks. In the worst case you check them all: a million numbers, a million checks.

But the list is sorted, so check the middle. If it's too small, the target can't be to its left, so the whole left half goes at once. Too big? The right half goes. Every check throws away half of what's left.

Let's find seventy-two. Low starts at zero, high at fourteen, so mid is seven: forty-one. Too small, so low jumps to eight. Mid is eleven: eighty. Too big, so high drops to ten. Mid is nine: sixty-four. Too small, so low moves to ten. Now low and high are both ten. Mid is ten: seventy-two. Found it in four checks, not eleven.

Now a miss: search for twenty. Mid is forty-one, too big, so high drops to six. Mid is seventeen, too small, so low goes to four. Twenty-nine, too big. Twenty-three, too big, and high drops to three, below low. The range is empty, so return minus one.

In code, loop while low is at most high. Not less than: when they meet, one number is still left, like seventy-two was. Mid is their average, rounded down. If it's the target, return it. Otherwise move low to mid plus one, or high to mid minus one. The plus one matters: with just mid, two numbers left could loop forever.

Each check halves the range, so the time is O of log n. A million numbers take at most twenty checks, because two to the twentieth is just over a million. And the space is constant: three pointers.

Check the middle, drop half, repeat. That's Binary Search.