Skip to main content

Foundations

Every binary search is one loop that shrinks a range until a single boundary is left. The primitives on this page return that boundary, and every other binary search page calls one of them.

The map​

Every ±1 in the loop comes from two independent choices: how you write the range, and which boundary you want.

Range - what are the smallest and largest answers the problem can return? Those are lo and hi.

  • Can the answer be "none", one past the end? → Half-open [lo, hi), hi = n. The default, and what Python's bisect uses.
  • Must the answer be a real index? → Closed [lo, hi], hi = n - 1. Never returns n, so check a[lo] after the loop.

Bound - which boundary do you want?

  • First >= x? → Lower, tests a[mid] < x.
  • First > x? → Upper, tests a[mid] <= x.
Binary search
Range
how you write the range
closed [lo, hi]
hi = n - 1
half-open [lo, hi)
hi = n
open (lo, hi)
lo = -1, hi = n
Bound
which boundary you want
lower
first >= x, test a[mid] < x
upper
first > x, test a[mid] <= x
last <= x
upper - 1

Bisect​

bisect_left(a, target) and bisect_right(a, target) both return an insert position: an index from 0 to n = len(a) where target could go and keep a sorted. When target repeats, bisect_left lands before the copies and bisect_right lands after them. Both cost O(log n).

Below, bisect_left and bisect_right stand for the two results. Think of them as two cuts in the array. The diagram builds down in levels, and each level answers one question using only the cuts and the levels above it.

1bisectwhere are the cuts?2find targetis target here?3insertwhere does it go?4neighbourswhat sits by a cut?5closestwhich is nearest?6counthow many?asorted, target = 3102122333435363738395108111012bisect_left → 3bisect_right → 10a[bisect_left] == targetfirst copy: bisect_leftlast copy: bisect_right - 1if bisect_left < n3before the copiesbisect_left3after the copiesbisect_rightany index 0..n is valid, no guardlargest < targetif bisect_left > 0a[bisect_left-1]smallest >= targetif bisect_left < na[bisect_left]largest <= targetif bisect_right > 0a[bisect_right-1]smallest > targetif bisect_right < na[bisect_right]a[bisect_left-1]vs a[bisect_left]the one nearer target winseach read needs its level 4 guard< targetbisect_left== targetbisect_right - bisect_left> targetn - bisect_right<= targetbisect_right>= targetn - bisect_left
target = 3. The two orange cuts run through every level; amber marks the guard a read needs.

A range count is two of the counts in level 6: how many <= hi minus how many < lo, so bisect_right(a, hi) - bisect_left(a, lo).

Guards. Reading a cell next to a cut can fall off the array: a[bisect_left] and a[bisect_right] need the cut to be < n, and a[bisect_left - 1] and a[bisect_right - 1] need it to be > 0. Counts and insert positions need no guard, since every value from 0 to n is valid.

Bisect Left​

Bisect Left

Easy

Lower-Bound Insert

FIG. BISECT LEFT● INTERACTIVE
visualization loads as you reach it
def bisect_left(arr, target, lo: int = 0, hi: int = None, *, key=None) -> int:
if lo < 0:
raise ValueError("lo must be >= 0")
if hi is None:
hi = len(arr) # always half-open [lo, hi)
if key is None: # costs a function call per iteration; Split Loops avoids it
key = lambda x: x
 
while lo < hi:
mid = lo + (hi - lo) // 2
if key(arr[mid]) < target: # stop at the first element >= target (leftmost slot)
lo = mid + 1
else:
hi = mid
 
return lo
top ↑

Bisect Right​

Bisect Right

Easy

Upper-Bound Insert

FIG. BISECT RIGHT● INTERACTIVE
visualization loads as you reach it
def bisect_right(arr, target, lo: int = 0, hi: int = None, *, key=None) -> int:
if lo < 0:
raise ValueError("lo must be >= 0")
if hi is None:
hi = len(arr) # always half-open [lo, hi)
if key is None: # costs a function call per iteration; Split Loops avoids it
key = lambda x: x
 
while lo < hi:
mid = lo + (hi - lo) // 2
if key(arr[mid]) <= target: # skip past elements equal to target (rightmost slot)
lo = mid + 1
else:
hi = mid
 
return lo
top ↑

Descending​

The same two primitives on a descending array: reuse them with key=lambda x: -x, or flip the comparison.

Bisect Left Reverse​

Bisect Left Reverse

Easy

Flipped Comparison

def bisect_left_rev(arr, target, lo: int = 0, hi: int = None) -> int:
if lo < 0:
raise ValueError("lo must be >= 0")
if hi is None:
hi = len(arr)
 
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] > target: # flipped: skip elements larger than target (leftmost slot)
lo = mid + 1
else:
hi = mid
 
return lo
top ↑

Bisect Right Reverse​

Bisect Right Reverse

Easy

Flipped Comparison

def bisect_right_rev(arr, target, lo: int = 0, hi: int = None) -> int:
if lo < 0:
raise ValueError("lo must be >= 0")
if hi is None:
hi = len(arr)
 
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] >= target: # flipped: skip elements >= target (rightmost slot)
lo = mid + 1
else:
hi = mid
 
return lo
top ↑

Applications​

The lower-bound template applied directly: on a plain array, an array with no known end, and a 2D grid read as one sorted list.

704. Binary Search

LeetCode
Easy

Lower-Bound (bisect_left)

FIG. 704 BINARY SEARCH● INTERACTIVE
visualization loads as you reach it
class Solution:
def search(self, nums: list[int], target: int) -> int:
# Bisect Left
# Answers [0, len(nums)): a real index, so post-check nums[lo]
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
 
return lo if nums[lo] == target else -1
top ↑

35. Search Insert Position​

35. Search Insert Position

LeetCode
Easy

Lower-Bound (bisect_left)

FIG. 35 SEARCH INSERT POSITION● INTERACTIVE
visualization loads as you reach it
class Solution:
def searchInsert(self, nums: list[int], target: int) -> int:
# Answers [0, len(nums)]: inserting past the end is a valid answer
lo, hi = 0, len(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
top ↑

702. Search in a Sorted Array of Unknown Size​

702. Search in a Sorted Array of Unknown Size

LeetCode
Medium

Find the Boundary, then Search

FIG. 702 SEARCH IN A SORTED ARRAY OF UNKNOWN SIZE● INTERACTIVE
visualization loads as you reach it
class Solution:
def search(self, reader: "ArrayReader", target: int) -> int:
# Answers [0, hi]: galloping stops once reader.get(hi) >= target, so post-check reader.get(lo)
lo, hi = 0, 1
# Find the boundary indices such that the target lies in-between (low, high)
while target > reader.get(hi):
lo = hi
hi <<= 2
# Typical binary search
while lo < hi:
mid = lo + (hi - lo) // 2
if reader.get(mid) < target:
lo = mid + 1
else:
hi = mid
return lo if reader.get(lo) == target else -1
top ↑

74. Search a 2D Matrix​

74. Search a 2D Matrix

LeetCode
Medium

2D as 1D

FIG. 74 SEARCH A 2D MATRIX● INTERACTIVE
visualization loads as you reach it
class Solution:
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
# Answers [0, m * n): a real flat index, so post-check getElement(lo)
lo, hi = 0, m * n - 1
getElement = lambda i: matrix[i // n][i % n]
while lo < hi:
mid = lo + (hi - lo) // 2
if getElement(mid) < target:
lo = mid + 1
else:
hi = mid
return getElement(lo) == target
top ↑