Lesson 2 of 4
Binary search
On a sorted list, one look at the middle rules out half of what is left. Two small templates, one that finds a value and one that finds where a yes/no answer turns to yes, cover this whole family, rotated lists included.
Trace a binary search and say
lo,midandhiafter every lookWrite the find template and say why it never misses the target and always stops
Write the first-true template (
while lo < hi,hi = mid) and explain why it endsUse
bisect.bisect_leftandbisect.bisect_rightand say what each returnsFind the smallest item of a rotated sorted list, and search one by finding its sorted half
You are looking for order id 4,817 in a list of a million order ids, sorted from smallest to largest. The loop from module 1 checks them one by one: up to a million looks. A sorted list lets you skip almost all of them. That is the payoff for the sort from the previous lesson.
Think of the guessing game. I pick a whole number from 1 to 100, and after each guess I say "higher" or "lower". You guess 50 and I say "lower": 50 to 100 are gone after one guess. Each guess at the middle throws away half of what is left. At most 50 numbers survive the first guess, at most 25 the second, then 12, 6, 3 and 1. Six guesses leave one number, and the seventh names it, so you never need more than seven.
That game is binary search, named for the split in two at every look. This lesson writes it as two templates: fixed shapes of code that you reuse from problem to problem, changing only the question they ask. The first finds a value. The second finds where a yes/no answer turns from no to yes. Then both go to work on a rotated list: a sorted list cut in two, with the pieces swapped.
Halving a sorted list
On a sorted list, one look at the middle tells you which half to drop. Say we want 16 in [2, 5, 8, 12, 16, 23, 38]. The middle number is 12. 12 is smaller than 16, and the list is sorted, so every number left of 12 is smaller too. 16 can only be to the right of the middle.
The notebook, what the walk writes down as it goes, is two indexes. lo and hi are the first and last index of the range that could still hold the target. We write that range as lo..hi: every index from lo to hi, both included. At the start it is the whole list, 0 to 6.
Each pass of the loop computes mid = (lo + hi) // 2, the middle index of the range, and compares nums[mid] with the target. // divides and rounds down: (0 + 6) // 2 is 3, and (4 + 7) // 2 is 5, not 5.5.
Before you step through, guess: how many looks at the middle does it take to find 16 among these seven numbers?
def search(nums, target):lo, hi = 0, len(nums) - 1while lo <= hi:mid = (lo + hi) // 2if nums[mid] == target:return midif nums[mid] < target:lo = mid + 1else:hi = mid - 1return -1
(nothing printed yet)This loop is the find template, for the question "is this value here, and where?" Why is it right? Because of its promise, the sentence about the notebook that stays true after every pass.
It holds at the start, when the range is the whole list. Each move throws away only indexes that cannot hold the target: mid itself, which was checked, and the side beyond it, which is all too small or all too big. So the promise still holds after every pass, and when mid lands on the target we return it.
When the target is not there
What happens when the target is missing? No look ever finds it, so the loop must stop another way. Predict this one first.
This search prints lo, mid and hi on every pass, right after it computes mid, then the result. Type exactly what it prints, one line per print. 5 is not in the list.
def search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
print(lo, mid, hi)
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(search([1, 4, 6, 9, 11, 15, 20, 27], 5))
Now the same search on the list from the trace, for 13, which is not there. The widget draws the list as cells with lo, mid and hi as arrows. Cells dropped by a step turn coral, then fade. Readouts count the steps so far and the indexes still possible. Press Next step to make one comparison.
The loop stops when lo passes hi, because then the range is empty. By the promise, an empty range means the target is nowhere in the list, so -1 is right. Two details make this work, and getting either one wrong is a classic off-by-one bug:
while lo <= hi, not<. Whenlo == hithe range still holds one index, and that index still needs a look. In the widget's third step, index 4 was checked only because the loop allowslo == hi.mid + 1andmid - 1, nevermid.nums[mid]has been checked, so it leaves the range. That also makes the range lose at least one index every pass, so the loop always ends. Withlo = midinstead, a range from 3 to 4 whosenums[3]is too small keepsmidat 3 forever.
Here is the first bug in a function that looks finished:
This version runs the loop while lo < hi instead of while lo <= hi. Everything else is the find template:
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
What does search([3, 5, 9], 9) return?
Choose one answer, then check.
Now turn the list around. A leaderboard keeps its scores from highest to lowest. Which half do you drop when the middle score is bigger than the target? Put the lines in order. Two of the lines are the bugs from above.
A leaderboard keeps its scores sorted from highest to lowest, with no repeats. Put the lines in order to build find_score(scores, target), which returns the index of target, or -1 if it is not there. Indentation is already part of each line. Two of the lines do not belong.
Think first: in this list, if scores[mid] is bigger than the target, which side of mid can the target be on?
Add lines from the list below, in order.
while lo <= hi:lo = mid + 1while lo < hi:elif scores[mid] > target:else:return -1lo, hi = 0, len(scores) - 1def find_score(scores, target):if scores[mid] == target:hi = mid - 1mid = (lo + hi) // 2return midlo = mid
How many looks can it take? Each look leaves at most half of the range (rounded down): the 7 indexes above became 3, then 1, and that last index needed its own look, 3 in all. That is why no target in the widget takes more than 3 steps. The worst case is the number of halvings to reach one index, plus one look at it.
A sorted list holds 1,000,000 order ids. What is the largest number of looks (passes of the while lo <= hi loop) the find template can need, whether the id is there or not? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now write it from a blank editor. The list may be empty and may hold negative numbers; the template needs no special case for either.
An empty list sets hi to -1, so lo <= hi is false at once and the function returns -1. To recap: the find template keeps the promise "if the target is here, it is in lo..hi", looks at the middle, drops mid and one side, and stops when it finds the target or when lo passes hi.
The first index where the answer turns to yes
Many questions in this family are not "is it there?" but "where does it start?" A table has one partition per day. On some day a new column was added, and every later partition has it too. has_column[d] is True when day d's partition has the column: [False, False, False, False, True, True, True].
Read left to right, the answers are no for a while and then yes to the end. We want the first yes. The find template does not fit: there is no value to match, and any yes is not enough. So the second template, the first-true template, changes three things:
histarts at the length, one past the last index. If no day has the column, the answer is "none", and the length stands for it.- A yes sets
hi = mid, notmid - 1. That yes might be the first one, so it stays in the range. - The loop runs
while lo < hiand stops when one candidate (one possible answer) is left. That candidate is the answer.
A no still sets lo = mid + 1: a no is never the first yes. Before you step through, guess how many looks it takes to find day 4.
def first_true(has_column):lo, hi = 0, len(has_column)while lo < hi:mid = (lo + hi) // 2if has_column[mid]:hi = midelse:lo = mid + 1return lo
(nothing printed yet)Why does the loop always end? One step at a time:
- While
lo < hi,midis at leastloand less thanhi, because//rounds down. Withlo = 4andhi = 5,midis 4, never 5. - So both moves shrink the range.
hi = midlowershiby at least one.lo = mid + 1raisesloby at least one. - Neither move jumps past the other.
hi = midkeepshi >= lo, andlo = mid + 1keepslo <= hi. So the loop ends exactly whenlo == hi, with one candidate left, and the promise says it is the first yes.
Point 1 also means the search never reads past the end: mid is less than hi, and hi is at most the length, so has_column[mid] is always a real index. An empty list needs no special case either: lo and hi both start at 0, the loop never runs, and the answer is 0, "none".
A sorted list turns into yes/no answers with one condition. "Is values[i] at least the target?" reads no for the small values and yes from some index on. The first yes is where the target is, or where it would go. The widget below runs the first-true template with that condition on [2, 4, 4, 7, 9, 12] and target 4, which appears twice. Guess first: which of the two 4s does it return?
The next problem asks for exactly this condition. Return the index of the target, or the index where it would go to keep the list sorted. Both are the first index whose value is at least the target.
The answer never needed the target to be present. The first-true template finds a boundary, and the boundary exists whether or not the value does. The two templates side by side:
| Find a value | First yes | |
|---|---|---|
| Start | lo, hi = 0, len(nums) - 1 | lo, hi = 0, len(nums) |
| Loop | while lo <= hi: | while lo < hi: |
At mid | equal: return mid | yes: hi = mid |
| Otherwise | lo = mid + 1 or hi = mid - 1 | no: lo = mid + 1 |
| After the loop | return -1 | return lo |
Pick the template by the question. "Is x here, and where?" takes the find template. "Where does the yes start?" takes the first-true template: insert positions, first copies, the first bad build, and, in the next lesson, the smallest value that is enough.
bisect: the first-true search, built in
Python ships the first-true template in bisect, a module of the standard library (a file of ready-made functions that import bisect loads). It covers the two conditions that come up most:
bisect.bisect_left(nums, x)returns the first index withnums[i] >= x. That is search insert position in one call.bisect.bisect_right(nums, x)returns the first index withnums[i] > x: the index just past the last copy ofx.
When no index qualifies, both return the length. Both cost O(log n). In a sorted list the copies of x sit between those two indexes, so bisect_right(nums, x) - bisect_left(nums, x) counts the copies. Predict all three lines:
Type exactly what this prints. The list is sorted and holds three copies of 3.
from bisect import bisect_left, bisect_right
nums = [1, 3, 3, 3, 7]
print(bisect_left(nums, 3), bisect_right(nums, 3))
print(bisect_right(nums, 3) - bisect_left(nums, 3))
print(bisect_left(nums, 4), bisect_right(nums, 4))
Know both the loop and the call. When the task is binary search itself, write the loop. When the search is one step of a bigger problem, bisect is one line you can explain. Now write bisect_right's search yourself.
A job logs event times in seconds, sorted from earliest to latest, and a time can repeat. Write count_at_most(times, t), which returns how many events happened at or before time t. With times = [3, 5, 5, 8, 12], t = 5 gives 3.
The count is the first index whose time is bigger than t, or len(times) if there is none: that is what bisect_right returns. Write the first-true template yourself, without bisect. Then press Watch it run.
raise NotImplementedError, then press Run tests. Each check says what it expects.A rotated list: where is the smallest?
A rotated sorted list is a sorted list cut into two pieces, with the pieces swapped. Cut [1, 2, 4, 6, 8, 10, 12] before the 4 and you get [4, 6, 8, 10, 12, 1, 2]. It climbs, drops once, and climbs again. The cut can also come at the very start, which leaves the list sorted. In this lesson no value repeats.
The smallest item sits right after the drop, or at index 0 when there is no drop. To find it with the first-true template, we need a yes/no question that reads no before the drop and yes from the drop on. Compare each item with the last item, here 2:
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| item | 4 | 6 | 8 | 10 | 12 | 1 | 2 |
| item <= 2? | no | no | no | no | no | yes | yes |
Every item before the drop is bigger than the last item, and every item from the drop on is at most the last item. The items before the drop came from the top of the sorted list, and the items after it climb up to the last item. So the first yes is the smallest item, here 1 at index 5. The last item is always a yes, so the question works on every list: on a list that was never rotated, every item is a yes, and the first yes is index 0.
Two small changes to the template. The last item is always a yes, so "no yes at all" cannot happen, and hi starts at the last index, len(nums) - 1, not at the length. And we want the smallest value, not its index, so the function returns nums[lo]. Before you step through, guess which indexes the search looks at, and in what order.
def find_min(nums):last = nums[-1]lo, hi = 0, len(nums) - 1while lo < hi:mid = (lo + hi) // 2if nums[mid] <= last:hi = midelse:lo = mid + 1return nums[lo]
(nothing printed yet)Now write it from a blank editor.
Searching a rotated list
Now find a target in a rotated list: 2 in [4, 6, 8, 10, 12, 1, 2]. The plain rule breaks. The middle item is 10, bigger than 2, so plain binary search would drop the right half, and 2 is in the right half.
The fix: one half is always sorted. Split the range at mid into the left half lo..mid and the right half mid..hi. The list drops only once, so the drop sits in at most one of the halves, and the other is in plain ascending order.
Which half is sorted? Compare its ends. Every item before the drop is bigger than every item after it, so a drop inside lo..mid would make nums[lo] bigger than nums[mid]. If nums[lo] <= nums[mid], the left half is sorted; otherwise the right half is.
A sorted half says in one check whether it can hold the target. The left half holds values from nums[lo] to nums[mid], so the target can be there only if nums[lo] <= target < nums[mid]. That is a chained comparison from module 1: it means nums[lo] <= target and target < nums[mid], and the < leaves out nums[mid], which we already know is not the target. If the target can be there, keep the left half; if not, keep the right. A sorted right half works the same way, with nums[mid] < target <= nums[hi].
Before you step through, guess which side of the 10 the first pass keeps.
def search_rotated(nums, target):lo, hi = 0, len(nums) - 1while lo <= hi:mid = (lo + hi) // 2if nums[mid] == target:return midif nums[lo] <= nums[mid]:if nums[lo] <= target < nums[mid]:hi = mid - 1else:lo = mid + 1else:if nums[mid] < target <= nums[hi]:lo = mid + 1else:hi = mid - 1return -1
(nothing printed yet)Now make the one decision that matters, on a new list:
We search for 11 in the rotated list [9, 11, 2, 3, 5, 7, 8]. The first pass has lo = 0, hi = 6 and mid = 3, where nums[3] is 3. What does the rotated search do next?
Choose one answer, then check.
Now the full problem. Write it from a blank editor, and test it on a list with two items.
The <= in nums[lo] <= nums[mid] is what the two-item test checks. With two items in the range, mid equals lo, so the left half is one item, and one item is sorted. With <, search [3, 1] for 1: mid is 0, and 3 < 3 is false, so the code calls the right half sorted. It checks 3 < 1 <= 1, which is false, sets hi to -1 and returns -1, though 1 is at index 1.
Last, answer a likely follow-up out loud.
You wrote search insert position with the first-true template. The interviewer asks: why does this loop always stop, and why hi = mid here when the find template writes hi = mid - 1? Write what you would say, in a few plain sentences.
Saved in this browser as you type.