3 · First, last, and where it would go
In one sentence: instead of stopping when it hits
x, search for the edge where the list turns from “smaller thanx” to “at leastx”; that one position gives you the first copy, the last copy, the count, and where a missing value would go.
The problem it solves
Real sorted data repeats. A log sorted by time has many events in the same second; a price list has many items
at 8. Lesson 2’s search returns a copy, whichever one a mid lands on. On
a = [2, 8, 8, 8, 12, 16, 23, 38, 56, 72], with 8 at positions 1, 2 and 3:
lo=0 hi=10 mid=5 a[mid]=16 16 > 8: hi = mid
lo=0 hi=5 mid=2 a[mid]=8 8 == 8: found
2
Position 2 is the middle copy. That doesn’t answer the usual questions:
- Where does the first 8 start? (all events from second 8 on)
- Where does the last one end? (how many items cost 8)
- The value isn’t there: where would it go, so the list stays sorted?
The idea: search for an edge, not a value
Draw a line through the sorted list: everything left of it is < 8, everything right of it is >= 8. Because the
list is sorted there is exactly one such line, and the first position right of it is the first 8, if there is
an 8 at all. If there isn’t, it’s where 8 would go.
values: 2 | 8 8 8 12 16 23 38 56 72
index: 0 | 1 2 3 4 5 6 7 8 9
< 8 | >= 8
^ the edge: lower bound = 1
That position is called the lower bound of x: the first index whose value is >= x (or len(a) if every
value is smaller). A binary search can find an edge just as it finds a value, and it never needs to stop early.
How it works
Same window as lesson 2, new promise:
Everything left of
lois< x. Everything fromhion is>= x.
At the start nothing is on either side (lo = 0, hi = len(a)), so the promise holds. Each round looks at
a[mid] and moves one edge, keeping it true:
a[mid] | Move | Why the promise holds |
|---|---|---|
a[mid] < x | lo = mid + 1 | mid and everything left of it are < x |
a[mid] >= x | hi = mid | mid and everything right of it are >= x; mid may be the answer, and it’s kept as hi |
There’s no “equal: return” line. Finding an 8 at mid doesn’t mean it’s the first one, so an equal value
moves hi like a bigger one does. When the window is empty, lo == hi, and the two halves of the promise meet:
left of lo is < x, from lo on is >= x. lo is the edge.
def lower_bound(a, x):
"""First index i with a[i] >= x, or len(a) if there is none."""
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < x:
lo = mid + 1 # mid is too small: the edge is right of it
else:
hi = mid # a[mid] >= x: the edge is at mid or left of it
return lo # lo == hi: the edge
On the list above, looking for 8 (the animation’s rounds 1 to 4):
lo=0 hi=10 mid=5 a[mid]=16 16 >= 8: hi = mid
lo=0 hi=5 mid=2 a[mid]=8 8 >= 8: hi = mid
lo=0 hi=2 mid=1 a[mid]=8 8 >= 8: hi = mid
lo=0 hi=1 mid=0 a[mid]=2 2 < 8: lo = mid + 1
final window: lo=1 hi=1
1
The other edge: upper bound
Move the line one place in the question: everything <= 8 on the left, > 8 on the right. The first index
whose value is > x is the upper bound. The code is the same loop with one character changed,
a[mid] <= x instead of a[mid] < x, so an equal value now moves lo past it:
lo=0 hi=10 mid=5 a[mid]=16 16 > 8: hi = mid
lo=0 hi=5 mid=2 a[mid]=8 8 <= 8: lo = mid + 1
lo=3 hi=5 mid=4 a[mid]=12 12 > 8: hi = mid
lo=3 hi=4 mid=3 a[mid]=8 8 <= 8: lo = mid + 1
final window: lo=4 hi=4
4
Everything from two edges
The copies of x are exactly the positions from the lower bound up to (not including) the upper bound: a
half-open window again, [lower, upper).
| You want | From the edges | For 8 here |
|---|---|---|
| first copy | lower, if lower < len(a) and a[lower] == x, else -1 | 1 |
| last copy | upper - 1, if that’s >= 0 and a[upper - 1] == x, else -1 | 3 |
| how many | upper - lower | 3 |
where x would go | lower | 1 |
The checks in the first two rows matter when x is missing. For each x on the same list, real runs (the last
two columns are Python’s own bisect, below):
x lower upper first last insert count bi_left bi_right
1 0 0 -1 -1 0 0 0 0
8 1 4 1 3 1 3 1 4
10 4 4 -1 -1 4 0 4 4
99 10 10 -1 -1 10 0 10 10
A missing value has lower == upper: zero copies, and the edge is where it would go. That’s the promise
lesson 2 made: its search for 24 ended on an empty window at 6, and the lower bound of 24 in that list makes the
same four moves and returns 6. Inserting 24 there keeps the list sorted:
[2, 5, 8, 12, 16, 23, 24, 38, 56, 72, 91]
6
Why < here and <= there
Swap them and each gives the other’s answer, with no error:
lower_bound with <=: 4
first with <=: -1
upper_bound with <: 1
last with <: -1
first(a, 8) says 8 isn’t in the list. To choose, ask what an equal value should do. For the first copy, an
equal a[mid] might have more copies left of it, so it stays in play: hi = mid (< sends only smaller values
right). For the last copy, more copies may be right of it: lo = mid + 1 (<= sends equal values right too).
Both versions agree with Python’s bisect on 10,000 random lists full of repeats; the swapped ones don’t:
lists: 10000 queries: 120000 mismatches: 0
bug_le lower_bound vs bisect_left: queries: 120000 mismatches: 80120
Try it on your computer
The capstone, Practical 1 · Capstone: range counts from an empty folder, has you write
lower_bound, upper_bound, first, last and insert_at from an empty folder, then a tool that counts the
events between two times with two searches, and swap a < to watch the checker catch it.
Go deeper: Python's bisect module
The standard library has both edges, in C: bisect.bisect_left(a, x) is the lower bound and
bisect.bisect_right(a, x) (also called bisect.bisect) the upper bound. The
documentation states the same promise as
above: for ip = bisect_left(a, x), every element of a[lo:ip] is < x and every element of a[ip:hi] is
>= x. Both take optional lo and hi to search part of a list.
Since Python 3.10 they take key=, to search records by one field. The key is applied to the list’s elements,
not to x, so you pass the time itself, not a record (lambda e: e[0] is a one-line function that returns
the first item of each record):
import bisect
events = [(5, 'boot'), (12, 'login'), (12, 'click'), (30, 'logout'), (41, 'boot')]
bisect.bisect_left(events, 12, key=lambda e: e[0]) # 1: first event at time 12
bisect.bisect_right(events, 12, key=lambda e: e[0]) # 3: first event after 12
bisect.insort(a, x) finds the place and inserts there. The search is fast, but inserting into a Python list
shifts everything after it, so the docs say its cost grows in proportion to the list’s length (written O(n)):
fine for a list you search often and change rarely. insort puts a new value after its equal copies (it’s
insort_right, the upper bound); insort_left puts it before them:
[(8, 'old'), (8, 'new')]
[(8, 'new'), (8, 'old')]
Go deeper: no early exit, and why that's fine
Lesson 2’s search can stop the moment a[mid] == x. The bounds never stop early: they always run until the
window is empty. On a million sorted numbers, over 1,009 searches:
lower_bound: queries=1009 min rounds=19 max rounds=20 rounds for x=a[500000]=1000000: 19
search: queries=1009 min rounds=10 max rounds=20 rounds for x=a[500000]=1000000: 1
search stops after one round for the value at the first mid, but over these 1,009 values it never took fewer
than 10, and its worst case is the same 20. The bounds cost 19 or 20 rounds every time and in return give an
answer that search can’t: the edge. Python’s bisect searches return only the edges; its documentation builds “is x
there?” on top of bisect_left, as the first-copy row above does: a[lower] == x.
Common misunderstandings
- “Lower bound returns -1 when
xis missing.” It returns a position in every case, from0tolen(a): wherexis, or where it would go. “Missing” is a separate check,a[i] == x. - “
len(a)is an error.” It’s the right answer when every value is smaller thanx: the edge is after the end. Checki < len(a)before readinga[i].
Check yourself
1. On the list above, what do lower_bound(a, 13) and upper_bound(a, 13) return, and what does that tell you?
Both return 5: 12 at position 4 is smaller than 13, and 16 at position 5 is bigger. lower == upper means there are no 13s, and 5 is where 13 would go, between 12 and 16.2. A log of events is sorted by time. How do you count the events with a time from A up to and including B, with two searches?
upper_bound(times, B) - lower_bound(times, A). The lower bound of A is the first event at A or later; the upper bound of B is the first event after B. Everything between them is in range. The capstone builds exactly this.3. In lower_bound, a colleague writes hi = mid - 1 in the else branch "to skip mid, since we already looked at it". What goes wrong?
mid may be the answer: a[mid] >= x, and it could be the first such position. hi = mid keeps it as the edge's
candidate. hi = mid - 1 leaves the window [lo, mid - 1), so both mid - 1 and mid are dropped. On the list above it
still gets 8 right (1) by luck, but lower_bound(a, 16) returns 4, the 12, instead of 5. It's lesson 2's third
Check yourself question in a new place.
Next: Practical 1 · Capstone: range counts from an empty folder.