iq.lab
Python starts when a code cell comes near or you run one
06 Sorting and binary search

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.

About 2 hours, with the 4 problems worked in it
By the end you can
  • Trace a binary search and say lo, mid and hi after every look

  • Write 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 ends

  • Use bisect.bisect_left and bisect.bisect_right and say what each returns

  • Find 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?

Step throughBinary search for 16
Step 1 of 18
Line 1 is about to run.
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
Names
no names yet
Output
(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.

PredictA search that finds nothing

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 <. When lo == hi the 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 allows lo == hi.
  • mid + 1 and mid - 1, never mid. 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. With lo = mid instead, a range from 3 to 4 whose nums[3] is too small keeps mid at 3 forever.

Here is the first bug in a function that looks finished:

Quick checkOne character changed

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.

Put in orderScores from highest to lowest

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?

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • while lo <= hi:
    • lo = mid + 1
    • while lo < hi:
    • elif scores[mid] > target:
    • else:
    • return -1
    • lo, hi = 0, len(scores) - 1
    • def find_score(scores, target):
    • if scores[mid] == target:
    • hi = mid - 1
    • mid = (lo + hi) // 2
    • return mid
    • lo = 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.

    Work it outA million ids

    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.

    looks

    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.

    easyBinary search target 15 min

    The list nums holds different integers in order from smallest to largest. Find target in it and return its position (index). When target does not appear, return -1.

    Each call must take O(log n) time, where n is the length of the list and log n is how many times n can be halved before it reaches 1. For a million numbers that is about 20 looks, so you cannot check every number.

    Example 1
    Inputnums = [-4, 0, 2, 5, 8, 13], target = 5Output3

    nums[3] is 5.

    Example 2
    Inputnums = [-4, 0, 2, 5, 8, 13], target = 6Output-1

    6 would sit between 5 and 8, but it is not in the list.

    Constraints
    • 0 ≤ len(nums) ≤ 105

    • -109 ≤ nums[i], target ≤ 109

    • nums is sorted in ascending order with no repeats.

    • Each call: O(log n) time.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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:

    1. hi starts at the length, one past the last index. If no day has the column, the answer is "none", and the length stands for it.
    2. A yes sets hi = mid, not mid - 1. That yes might be the first one, so it stays in the range.
    3. The loop runs while lo < hi and 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.

    Step throughThe first day with the new column
    Step 1 of 18
    Line 1 is about to run.
    def first_true(has_column):
    lo, hi = 0, len(has_column)
    while lo < hi:
    mid = (lo + hi) // 2
    if has_column[mid]:
    hi = mid
    else:
    lo = mid + 1
    return lo
    Names
    no names yet
    Output
    (nothing printed yet)

    Why does the loop always end? One step at a time:

    1. While lo < hi, mid is at least lo and less than hi, because // rounds down. With lo = 4 and hi = 5, mid is 4, never 5.
    2. So both moves shrink the range. hi = mid lowers hi by at least one. lo = mid + 1 raises lo by at least one.
    3. Neither move jumps past the other. hi = mid keeps hi >= lo, and lo = mid + 1 keeps lo <= hi. So the loop ends exactly when lo == 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.

    easyBinary search target 15 min

    Search insert position

    The list nums holds different integers in order from smallest to largest. Return the index where target belongs: the first index whose number is at least target, or len(nums) (one past the last index) when every number is smaller.

    That one rule covers both cases. If target is already in the list, the answer is its own index. If it is missing, the answer is the spot where inserting target keeps the list in order. Each call must take O(log n) time, where n is the length of the list and log n is how many times n can be halved before it reaches 1.

    Example 1
    Inputnums = [1, 4, 6, 9], target = 5Output2

    5 belongs between 4 and 6. It would take index 2 and push 6 to the right.

    Example 2
    Inputnums = [1, 4, 6, 9], target = 6Output2

    6 is already at index 2.

    Example 3
    Inputnums = [1, 4, 6, 9], target = 12Output4

    Every number is smaller, so 12 goes at the end: index 4, the length of the list.

    Constraints
    • 0 ≤ len(nums) ≤ 105

    • -109 ≤ nums[i], target ≤ 109

    • nums is sorted in ascending order with no repeats.

    • Each call: O(log n) time.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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 valueFirst yes
    Startlo, hi = 0, len(nums) - 1lo, hi = 0, len(nums)
    Loopwhile lo <= hi:while lo < hi:
    At midequal: return midyes: hi = mid
    Otherwiselo = mid + 1 or hi = mid - 1no: lo = mid + 1
    After the loopreturn -1return 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 with nums[i] >= x. That is search insert position in one call.
    • bisect.bisect_right(nums, x) returns the first index with nums[i] > x: the index just past the last copy of x.

    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:

    PredictLeft and right

    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.

    Code itEvents up to a time

    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.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says 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:

    index0123456
    item468101212
    item <= 2?nononononoyesyes

    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.

    Step throughThe smallest item of a rotated list
    Step 1 of 19
    Line 1 is about to run.
    def find_min(nums):
    last = nums[-1]
    lo, hi = 0, len(nums) - 1
    while lo < hi:
    mid = (lo + hi) // 2
    if nums[mid] <= last:
    hi = mid
    else:
    lo = mid + 1
    return nums[lo]
    Names
    no names yet
    Output
    (nothing printed yet)

    Now write it from a blank editor.

    mediumBinary search target 25 min

    Minimum of a rotated sorted list

    A list of distinct integers was sorted from small to large and then rotated: some items were taken off the front and put on the back, keeping their order. Moving the first two items of [1, 3, 5, 7, 9] to the back gives [5, 7, 9, 1, 3]. The number of items moved can be zero, which leaves the list sorted.

    You get the rotated list nums. Your function returns the smallest number in it (the value, not its index).

    Reading every item gives the right answer but fails the speed test. Aim for O(log n) time, the cost of a binary search.

    Example 1
    Inputnums = [5, 7, 9, 1, 3]Output1

    The sorted list [1, 3, 5, 7, 9] had its first two items moved to the back.

    Example 2
    Inputnums = [8, 2, 4, 6]Output2

    The list drops from 8 to 2 and then climbs. The smallest sits right after the drop.

    Example 3
    Inputnums = [2, 4, 6, 8]Output2

    No items moved, so there is no drop and the first item is the smallest.

    Constraints
    • 1 ≤ len(nums) ≤ 40,000,000

    • The values are distinct integers.

    • The speed test passes a list-like object with 40,000,000 items that computes each item when you read it. It supports len(nums) and nums[i] (negative i too) but not slicing. Reading all of its items takes seconds.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Step throughSearch a rotated list for 2
    Step 1 of 20
    Line 1 is about to run.
    def search_rotated(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
    mid = (lo + hi) // 2
    if nums[mid] == target:
    return mid
    if nums[lo] <= nums[mid]:
    if nums[lo] <= target < nums[mid]:
    hi = mid - 1
    else:
    lo = mid + 1
    else:
    if nums[mid] < target <= nums[hi]:
    lo = mid + 1
    else:
    hi = mid - 1
    return -1
    Names
    no names yet
    Output
    (nothing printed yet)

    Now make the one decision that matters, on a new list:

    Quick checkWhich half is sorted?

    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.

    mediumBinary search target 25 min

    Search a rotated sorted list

    Start with different integers in order from smallest to largest. Cut the list into two pieces and swap the pieces: that is a rotated list. For example, [1, 2, 4, 6, 7, 9] cut before the 6 becomes [6, 7, 9, 1, 2, 4]. The cut may also be at the very start, which leaves the list in order.

    You get the rotated list nums and a number target. Find target and return its index; when it does not appear, return -1. Each call must take O(log n) time, where n is the length of the list and log n is how many times n can be halved before it reaches 1. A scan of the whole list is too slow.

    Example 1
    Inputnums = [6, 7, 9, 1, 2, 4], target = 2Output4

    2 is in the second piece, at index 4.

    Example 2
    Inputnums = [6, 7, 9, 1, 2, 4], target = 8Output-1

    8 is not in the list.

    Example 3
    Inputnums = [1, 3, 5], target = 5Output2

    A cut at the start leaves the list sorted, and 5 is at index 2.

    Constraints
    • 1 ≤ len(nums) ≤ 105

    • -109 ≤ nums[i], target ≤ 109

    • All numbers in nums are different.

    • nums is a sorted list rotated at some position, possibly 0.

    • Each call: O(log n) time.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Say itWhy does it stop?

    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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Binary search on the answer