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 < hitemplate:histarts atlen(a), one past the end, meaning "maybe nothing passes"; the loop runs whilelo < hiand ends withlo == hi
Step by step, for the first item that is at least x:
lo, hi = 0, len(a)- while
lo < hi:mid = (lo + hi) // 2 a[mid] >= x(True)? The first True is mid or to its left:hi = mid, keeping mid in- False? The first True is to the right:
lo = mid + 1 - return
lo: the first item at least x, orlen(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 = midon 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 - 1in thelo < hitemplate: it can jump over the edge when mid was the first Truelo = midinstead oflo = mid + 1: with two items left, mid equals lo again and the loop never ends- the value isn't there:
first_at_leaststill returns where it would go; checklo < len(a) and a[lo] == xbefore 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
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)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)
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 loHow 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
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
Write
first_at_least(nums, x)for a sorted list: the position of the first item that is at least x, orlen(nums)if there is none. Use the lo < hi template: on 3000 items it may compare at most 30 times.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.