Python 3D Academyবাংলা

Getting the boundaries right: the first and the last

🌍 In real life. The class register lists every student by their test mark, from lowest to highest, and many students share a mark. The teacher asks two questions: who is the first student with 80 or more? and how many students got exactly 80? Finding some 80 is not enough any more: you need the edges of the block of 80s.

Think of the register with a yes/no question beside each name: "is this mark 80 or more?" Because the marks are sorted, the answers go no, no, no, …, yes, yes, yes: once yes, always yes. The first student with 80 or more is the first yes, and binary search can find that edge directly.

The idea in one sentence: to find the first position where a sorted list passes a test that goes False … False, True … True, keep lo before the edge and hi on or after it, and close them in until lo == hi, the edge.

Its words:

  • boundary (or edge): the first position where the test is True
  • the lo < hi template: hi starts at len(a), one past the end, meaning "maybe nothing passes"; the loop runs while lo < hi and ends with lo == hi

Step by step, for the first item that is at least x:

  1. lo, hi = 0, len(a)
  2. while lo < hi: mid = (lo + hi) // 2
  3. a[mid] >= x (True)? The first True is mid or to its left: hi = mid, keeping mid in
  4. False? The first True is to the right: lo = mid + 1
  5. return lo: the first item at least x, or len(a) if there is none

The last x is just before the first item bigger than x: the same loop with the test a[mid] > x, minus one. Here are both on the same marks:

Why it is correct. Two facts stay true before every look: everything before lo fails the test, and everything from hi on passes it (at the start, nothing is before 0 and nothing is from len(a) on, so both hold). A True at mid means the edge is at mid or before, so hi = mid keeps both facts; a False means it is after mid, so lo = mid + 1 keeps them too. When lo == hi, the item at lo is the first that passes. And mid is always below hi, so every look shrinks the range: no endless loop.

The two templates.

  • lo <= hi, hi = len(a) - 1, moving past mid both ways: for "is it there, and where?" (Lesson 43.1)
  • lo < hi, hi = len(a), hi = mid on True: for "where is the first True?". It answers more questions: the first and last of a value, where to insert, and (in Lesson 43.3) the smallest answer that is good enough

What it costs. Each look halves the range: O(log n). Counting a value is two boundary searches, last edge minus first edge: still O(log n), where nums.count(x) checks every item, O(n). In the library: bisect_left(a, x) is the first edge and bisect_right(a, x) the edge after the last x, so the count is their difference.

import bisect

def first_at_least(a, x):
    lo, hi = 0, len(a)               # hi: one past the end
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] >= x:
            hi = mid                 # mid might be the first: keep it
        else:
            lo = mid + 1
    return lo

def first_above(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] > x:
            hi = mid
        else:
            lo = mid + 1
    return lo

marks = [1, 3, 3, 3, 5, 8]
print(first_at_least(marks, 3), first_above(marks, 3) - 1)
print(first_above(marks, 3) - first_at_least(marks, 3))   # how many 3s
print(first_at_least(marks, 9), first_at_least(marks, 0))
print(bisect.bisect_left(marks, 3), bisect.bisect_right(marks, 3))

Mistakes and edge cases.

  • hi = mid - 1 in the lo < hi template: it can jump over the edge when mid was the first True
  • lo = mid instead of lo = mid + 1: with two items left, mid equals lo again and the loop never ends
  • the value isn't there: first_at_least still returns where it would go; check lo < len(a) and a[lo] == x before treating it as found
  • nothing passes: the answer is len(a), one past the end, so don't index the list with it without checking

Quiz

  1. What does this print?

    a = [2, 4, 4, 4, 4, 7, 9]
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] > 4:
            hi = mid
        else:
            lo = mid + 1
    print(lo, lo - 1)
  2. In the lo < hi template, why is it hi = mid (not mid - 1) when the test is True at mid?

    • mid itself might be the first True, so it must stay in the range
    • To make the loop faster
    • Because hi started at len(a)
  3. first_at_least([1, 3, 5], 5) never finishes. Which line is wrong?

    def first_at_least(a, x):
        lo, hi = 0, len(a)
        while lo < hi:
            mid = (lo + hi) // 2
            if a[mid] >= x:
                hi = mid
            else:
                lo = mid
        return lo
  4. How do you count how many times x is in a sorted list in O(log n)?

    • The first position above x minus the first position at least x
    • nums.count(x)
    • Find one x, then walk left and right
  5. first_at_least(a, x) returns len(a). What does that mean?

    • Every item is smaller than x
    • x is the last item
    • The list is empty

Coding tasks

  1. Write first_at_least(nums, x) for a sorted list: the position of the first item that is at least x, or len(nums) if there is none. Use the lo < hi template: on 3000 items it may compare at most 30 times.

  2. Write count_of(nums, x): how many times x appears in a sorted list, with two boundary searches (the first item at least x, and the first item above x). On 2000 items it may compare at most 60 times.