Binary search bounds and bisect
The lower bound is the first position whose value is ≥ x and the upper bound the first whose value is > x; Python's bisect_left and bisect_right return exactly these, and their difference is how many times x appears.
A sorted score list [58, 60, 60, 72, 85, 85, 85, 91], and the questions are "who is the first to pass?", "how many scored 85?", "what is the highest score below 80?". Last lesson's binary search only answers "is it there?", and with repeats which one it finds is luck: look for 60 and it returns index 2, but the first 60 is at index 1. What interviews and real code use most are two binary searches that only look for a boundary: lower bound and upper bound. Python's bisect_left and bisect_right are exactly these.
The first ≥ x: lower bound
Ask it another way: a sorted list can always be cut into two runs, everything on the left < x and everything on the right ≥ x. We want the line between them, the first index of the right run. This question always has an answer: when x is bigger than everything, the right run is empty and the line is at len(a).
Still half-open, but this time it means "the line is somewhere in [lo, hi]", and the loop stops at lo == hi:
a[mid] < x: mid is in the left run, the line is right of it,lo = mid + 1.- Otherwise mid is in the right run, the line is at mid or further left,
hi = mid. mid itself may be the answer, so notmid - 1. - No equality check: finding an x doesn't stop it; it keeps pushing left until lo and hi meet.
lo↑hi↑mid1lo, hi = 0, len(a)2while lo < hi:3 mid = (lo + hi) // 24 if a[mid] < x:5 lo = mid + 16 else:7 hi = mid8return lo
Use lower bound to look for 7 in 2 4 4 4 7 9 (n = 6). Which mids does it look at, and what does it return?
Why does lower bound not have if a[mid] == x: return mid?
58 60 60 72 85 85 85 91, the first mid = 4 happens to be 85. But for 60 the first hit is index 2, while the first 60 is at index 1. Without the equality check, hitting x counts as "right part", hi = mid keeps shrinking leftwards, and where lo and hi meet is the boundary.The first > x: upper bound
Change one character: a[mid] < x becomes a[mid] <= x. Values equal to x now count as the left run too, and the line becomes the position of the first > x.
lo↑hi↑mid1lo, hi = 0, len(a)2while lo < hi:3 mid = (lo + hi) // 24 if a[mid] <= x:5 lo = mid + 16 else:7 hi = mid8return lo
With these two, every boundary question can be put together:
| You want | How | In the score list |
|---|---|---|
| The first ≥ x | lower(a, x) | x = 60: index 1 |
| The first > x | upper(a, x) | x = 60: index 3 |
| Where x first appears | i = lower(a, x), check a[i] == x | 85: index 4 |
| Where x last appears | upper(a, x) - 1, check it is x | 85: index 6 |
| How many x | upper(a, x) - lower(a, x) | 85: 3 |
| The last ≤ x | a[upper(a, x) - 1] | x = 80: 72 |
| Where to insert x | lower before the equal ones, upper after | 70: index 3 |
1def lower(a, x): # the first >= x2 lo, hi = 0, len(a)3 while lo < hi:4 mid = (lo + hi) // 25 if a[mid] < x:6 lo = mid + 17 else:8 hi = mid9 return lo10 11def upper(a, x): # the first > x12 lo, hi = 0, len(a)13 while lo < hi:14 mid = (lo + hi) // 215 if a[mid] <= x:16 lo = mid + 117 else:18 hi = mid19 return lo20 21def first_last(a, x):22 i = lower(a, x)23 if i == len(a) or a[i] != x: # the line isn't on an x: x isn't there24 return -1, -125 return i, upper(a, x) - 126 27a = [58, 60, 60, 72, 85, 85, 85, 91]28print("index of the first pass:", lower(a, 60))29print("positions of 85:", first_last(a, 85), "count", upper(a, 85) - lower(a, 85))30print("positions of 70:", first_last(a, 70), "count", upper(a, 70) - lower(a, 70))31print("highest score below 80:", a[upper(a, 80) - 1])32print(lower(a, 50), lower(a, 99)) # smaller than all: 0; bigger than all: len(a)
index of the first pass: 1 positions of 85: (4, 6) count 3 positions of 70: (-1, -1) count 0 highest score below 80: 72 0 8
Counting a value with a.count(85) counts from front to back, O(n); two binary searches are O(log n). With a million values, one looks a million times, the other 40 times.
Boundaries in 2 4 4 4 7 9. What does it print?
1def lower(a, x):2 lo, hi = 0, len(a)3 while lo < hi:4 mid = (lo + hi) // 25 if a[mid] < x:6 lo = mid + 17 else:8 hi = mid9 return lo10 11def upper(a, x):12 lo, hi = 0, len(a)13 while lo < hi:14 mid = (lo + hi) // 215 if a[mid] <= x:16 lo = mid + 117 else:18 hi = mid19 return lo20 21b = [2, 4, 4, 4, 7, 9]22print(lower(b, 4), upper(b, 4), lower(b, 5), upper(b, 10))
a = 1 3 3 3 5 8, x = 3. What are lower bound(x) and upper bound(x)?
To turn lower bound into upper bound (the first > x), what goes in the condition? The program prints how many times 85 appears and the index of the first > 60: it should be 3 3.
1def lower(a, x):2 lo, hi = 0, len(a)3 while lo < hi:4 mid = (lo + hi) // 25 if a[mid] < x:6 lo = mid + 17 else:8 hi = mid9 return lo10 11def upper(a, x):12 lo, hi = 0, len(a)13 while lo < hi:14 mid = (lo + hi) // 215 if a[mid] x:16 lo = mid + 117 else:18 hi = mid19 return lo20 21a = [58, 60, 60, 72, 85, 85, 85, 91]22print(upper(a, 85) - lower(a, 85), upper(a, 60))
a[mid] <= x, mid is still in the left part, so lo = mid + 1. With < it's back to lower bound, and the count of 85s comes out 0.First and last position
✓Complete search_range(a, x): a is sorted from small to large; return the first and last index of x as [first, last], or [-1, -1] if it isn't there. lower is already written; without bisect, write an upper yourself.
[3, 5] [1, 2] [6, 6] [-1, -1] [-1, -1] [-1, -1]
1def lower(a, x):2 lo, hi = 0, len(a)3 while lo < hi:4 mid = (lo + hi) // 25 if a[mid] < x:6 lo = mid + 17 else:8 hi = mid9 return lo10 11def search_range(a, x):12 # first comes from lower; check a[first] is x; last is upper - 113 return [-1, -1]14 15a = [5, 7, 7, 8, 8, 8, 10]16print(search_range(a, 8), search_range(a, 7), search_range(a, 10))17print(search_range(a, 6), search_range(a, 11), search_range([], 0))
The bisect module
The standard library's bisect has both ready-made, written in C, faster than the hand-written ones:
| Function | Same as | Returns |
|---|---|---|
bisect_left(a, x) | lower(a, x) | the position of the first ≥ x |
bisect_right(a, x), bisect(a, x) | upper(a, x) | the position of the first > x |
insort_left(a, x) | insert at bisect_left | nothing, inserts in place |
insort_right(a, x), insort(a, x) | insert at bisect_right | nothing, inserts in place |
All of them take lo= and hi= to search only part of the list. Since Python 3.10 they also take key=: when the list holds records sorted by one field, you don't need a second list of just that field. Note that for bisect_left x is the score (key isn't applied to x), while for insort x is the whole record (key is applied to x too):
1from bisect import bisect_left, bisect_right, insort2 3a = [58, 60, 60, 72, 85, 85, 85, 91]4print(bisect_left(a, 85), bisect_right(a, 85), bisect_right(a, 85) - bisect_left(a, 85))5print(bisect_left(a, 85, lo=5)) # search only in a[5:]6 7records = [("ann", 58), ("bob", 60), ("cat", 72), ("dan", 85), ("eve", 85), ("fay", 91)]8score = lambda r: r[1] # sorted by score9i = bisect_left(records, 85, key=score)10j = bisect_right(records, 85, key=score)11print(i, j, records[i:j])12insort(records, ("gus", 80), key=score)13print([name for name, s in records])
4 7 3
5
3 5 [('dan', 85), ('eve', 85)]
['ann', 'bob', 'cat', 'gus', 'dan', 'eve', 'fay']
The surest way to know the hand-written one matches bisect exactly is to compare them for every possible x:
1from bisect import bisect_left, bisect_right2 3def lower(a, x):4 lo, hi = 0, len(a)5 while lo < hi:6 mid = (lo + hi) // 27 if a[mid] < x:8 lo = mid + 19 else:10 hi = mid11 return lo12 13for a in [[], [5], [5, 5, 5], [1, 3, 3, 7, 9, 9]]:14 same = all(lower(a, x) == bisect_left(a, x) for x in range(11))15 print(a, same, [bisect_right(a, x) for x in [0, 3, 5, 9, 10]])
[] True [0, 0, 0, 0, 0] [5] True [0, 0, 1, 1, 1] [5, 5, 5] True [0, 0, 3, 3, 3] [1, 3, 3, 7, 9, 9] True [0, 3, 3, 6, 6]
records are sorted by score. key= pulls out the score to compare, and lo=2 searches only from index 2 on. What does this print?
1from bisect import bisect_left, bisect_right2 3records = [("ann", 58), ("bob", 60), ("dan", 85), ("eve", 85)]4i = bisect_right(records, 85, key=lambda r: r[1])5print(i, bisect_left(records, 60, lo=2, key=lambda r: r[1]))
lo=2, only indices 2 and 3 are looked at; both are ≥ 60, so it returns 2. Note that the result is an index into the whole list, not a count from lo.insort is still O(n)
insort finds the position in O(log n), but then it still has to a.insert(i, x): every element after it moves one place back.
lo↑hi↑midInsort 1000 numbers one by one, counting comparisons and moves separately:
1def insert_all(order):2 a = []3 cmps = moves = 04 for x in order:5 lo, hi = 0, len(a) # like insort: find the first > x6 while lo < hi:7 cmps += 18 mid = (lo + hi) // 29 if a[mid] <= x:10 lo = mid + 111 else:12 hi = mid13 moves += len(a) - lo # insert moves everything after it back one14 a.insert(lo, x)15 return cmps, moves16 17n = 100018print("small to large: comparisons, moves", insert_all(range(n)))19print("large to small: comparisons, moves", insert_all(range(n, 0, -1)))20print("n(n - 1) / 2 =", n * (n - 1) // 2)
small to large: comparisons, moves (7987, 0) large to small: comparisons, moves (8977, 499500) n(n - 1) / 2 = 499500
Under 9000 comparisons in all, n log n; inserting from large to small, every new number goes to the front, 499,500 moves, n²/2. So n insorts are O(n²) in the worst case. The moves are one block memory copy in C, fast up to tens of thousands; beyond that you need another structure (next lesson: balanced trees).
| Operation | Time | Note |
|---|---|---|
bisect_left / bisect_right | O(log n) | a must already be sorted |
insort | O(n) | finding O(log n), inserting moves O(n) |
a.count(x) | O(n) | counts from the front |
bisect_right − bisect_left | O(log n) | counting when sorted |
append everything, then sort() once | O(n log n) | fastest when you don't search while inserting |
In interviews: "find the first and last position of an element in a sorted array" is lower bound and upper bound − 1. Before writing, say which line you are looking for; hi = mid because mid itself may be the answer. When O(log n) is required, don't binary search for one match and then scan both ways: if every value is the same, that is O(n).
a = [1, 3, 5, 7, 9], then insort(a, 6). How many numbers have to shift one place right?
insert, and everything after it moves.A million log lines have to be sorted by time, and you query only after that. What's fastest?
sort() is O(n log n). Insorting each line adds up to O(n²) shifts in the worst case; sorting after every line is even worse. A set has no order, and it would also merge duplicate lines. insort only makes sense when you need to query while you're still inserting.How you write it at work
The three most common uses of bisect: turning a score into a grade, counting a range, and finding the closest value.
1from bisect import bisect_left, bisect_right2 3cuts = [60, 70, 80, 90] # the grade lines: sorted4def grade(score):5 return "FDCBA"[bisect_right(cuts, score)]6 7print([grade(s) for s in [33, 60, 75, 89, 90, 100]])8 9a = [58, 60, 60, 72, 85, 85, 85, 91]10def count_between(a, lo, hi): # how many with lo <= x <= hi11 return bisect_right(a, hi) - bisect_left(a, lo)12 13print(count_between(a, 60, 85), count_between(a, 61, 84), count_between(a, 0, 100))
['F', 'D', 'C', 'B', 'A', 'A'] 6 1 8
- Grades, tax brackets, shipping tiers, any "which band does it fall in" question: one
bisect_rightdoes it, with no chain ofif score >= 90 … elif …. A score exactly on a line (60, 90) goes to the higher band, which is exactlybisect_right's "equal counts as the left run". - Counting a range
[lo, hi]:bisect_right(a, hi)on the right (hi itself counts) andbisect_left(a, lo)on the left. - Data that keeps arriving while you search, more inserts than searches:
append, andsort()once before you search. Many searches and many inserts, over a few hundred thousand values: the third-partysortedcontainerslibrary, or a database index.
Same score, but bisect_right and bisect_left give different grades. What does this print?
1from bisect import bisect_left, bisect_right2 3cuts = [60, 70, 80, 90]4print("FDCBA"[bisect_right(cuts, 80)], "FDCBA"[bisect_left(cuts, 80)])
bisect_right counts an equal 80 in the left part and returns 3, and "FDCBA"[3] is B; bisect_left returns 80's own index, 2, which is C. "On the line goes up a grade" needs bisect_right.The closest value to x
✓Complete closest(a, x): a is sorted from small to large and not empty; return the value in a closest to x, and the smaller one on a tie. Use bisect_left and look only at the two values on either side of the line.
[1, 4, 6, 6, 10, 15, 15] 3
1from bisect import bisect_left2 3def closest(a, x):4 i = bisect_left(a, x)5 # the only candidates are a[i - 1] and a[i]: watch out for i == 0 and i == len(a)6 return a[0]7 8a = [1, 4, 6, 10, 15]9print([closest(a, x) for x in [0, 5, 7, 8, 12, 13, 99]])10print(closest([3], 100))
Summary
Binary search for a boundary: lower and upper
- lower: the first ≥ x (go right only when a[mid] < x); upper: the first > x (go right when a[mid] <= x)
- No equality check: where lo and hi meet is the line; "none" is len(a), not -1
- count = upper − lower; last position = upper − 1; always check x is there
- bisect_left / bisect_right are exactly these; key= searches by one field of a record
- insort finds the place in O(log n) and inserts in O(n)
1i = bisect_left(a, x) # the first >= x2j = bisect_right(a, x) # the first > x3count = j - i4found = i < len(a) and a[i] == x5insort(a, y) # O(n)