bisect#
Python’s built-in binary search module for querying and maintaining sorted lists in O(log N) search time.
Core Functions#
bisect.bisect_left(a: Sequence[T], x: T, lo: int = 0, hi: int = len(a)) -> int: First insertion indexiwherea[i] >= x(equivalent to C++std::lower_bound).bisect.bisect_right(a: Sequence[T], x: T, lo: int = 0, hi: int = len(a)) -> int: First insertion indexiwherea[i] > x(equivalent to C++std::upper_bound).bisect.bisectis an alias forbisect_right.bisect.insort_left(a: MutableSequence[T], x: T)/bisect.insort_right(a: MutableSequence[T], x: T): Insertsxintoawhile preserving sort order (O(log N)search,O(N)element shift).
Common Patterns#
from bisect import bisect_left, bisect_right
arr = [10, 20, 20, 20, 30]
# 1. Lower and upper bounds
lo = bisect_left(arr, 20) # 1 (first index >= 20)
hi = bisect_right(arr, 20) # 4 (first index > 20)
# 2. Count occurrences of a value in O(log N)
count = hi - lo # 3
# 3. Exact value lookup
idx = bisect_left(arr, 20)
exists = idx < len(arr) and arr[idx] == 20 # True
# 4. Greatest element <= target
pos = bisect_right(arr, 25) - 1 # index 3 -> value 20 (valid when pos >= 0)