Skip to main content

bisect_left and bisect_right

Binary search on a sorted list in O(log n). bisect_left(a, x) is the first index with a[i] >= x; bisect_right(a, x) is the first index with a[i] > x. Use them instead of hand-rolling lower/upper bound, and with key= (3.10+) to binary search on the answer.

Syntax​

from bisect import bisect_left, bisect_right

a = [1, 2, 2, 2, 5]
bisect_left(a, 2) # -> 1, first index with a[i] >= 2
bisect_right(a, 2) # -> 4, first index with a[i] > 2 (bisect == bisect_right)
bisect_left(a, 3) # -> 4, insertion point when missing
from bisect import bisect_left

def index_of(a: list[int], x: int) -> int:
i = bisect_left(a, x)
return i if i < len(a) and a[i] == x else -1

index_of([1, 3, 5], 3) # -> 1
index_of([1, 3, 5], 4) # -> -1

First and last occurrence (LeetCode 34)​

from bisect import bisect_left, bisect_right
a, x = [5, 7, 7, 8, 8, 10], 8
lo, hi = bisect_left(a, x), bisect_right(a, x) - 1
[lo, hi] if lo <= hi else [-1, -1] # -> [3, 4]
bisect_right(a, x) - bisect_left(a, x) # -> 2, count of x

Count elements in a range​

from bisect import bisect_left, bisect_right
a = [1, 3, 4, 6, 8, 9]
bisect_right(a, 8) - bisect_left(a, 3) # -> 4, count in [3, 8]
bisect_left(a, 5) # -> 3, count < 5
len(a) - bisect_right(a, 5) # -> 3, count > 5

Predecessor / successor​

from bisect import bisect_left, bisect_right
a = [10, 20, 30]
i = bisect_right(a, 25) - 1 # largest <= 25 -> a[1] == 20 (check i >= 0)
j = bisect_left(a, 25) # smallest >= 25 -> a[2] == 30 (check j < len(a))

lo and hi bounds​

from bisect import bisect_left
a = [1, 3, 5, 7, 9]
bisect_left(a, 5, lo=3) # -> 3, search only a[3:]
bisect_left(a, 5, lo=0, hi=2) # -> 2, search only a[:2]

key= (3.10+)​

from bisect import bisect_left
intervals = [(1, "a"), (4, "b"), (9, "c")] # sorted by first field
bisect_left(intervals, 4, key=lambda t: t[0]) # -> 1
# key applies to elements, NOT to x: pass the already-extracted key

Binary search on the answer​

from bisect import bisect_left
import math

# Koko Eating Bananas (LeetCode 875): smallest speed that finishes in h hours
piles, h = [3, 6, 7, 11], 8

def can_finish(k: int) -> bool:
return sum(math.ceil(p / k) for p in piles) <= h

# range is a lazy sequence; key maps each speed to False...False, True...True
bisect_left(range(1, max(piles) + 1), True, key=can_finish) + 1 # -> 4
# O(n log m), m = max(piles)

Docs​