Skip to main content

Boundaries & Counts

First position, last position, how many, what comes next. The array is sorted, so every one of these is read off one or two cuts.

Two cuts​

bisect_left(a, x) cuts before the copies of x, bisect_right(a, x) cuts after them. The full table of reads, level by level, is the cuts figure on Foundations.

left = bisect_left(a, x) # first index with a[i] >= x
right = bisect_right(a, x) # first index with a[i] > x
count = right - left # copies of x

Which read, which guard​

A count or an insert slot needs no guard: any value from 0 to n is valid. A read of a[cut] needs cut < n, and a[cut - 1] needs cut > 0. Wrap-around problems (744) fall back to a[0] when the cut hits n.

One cut, read a neighbour​

The answer sits right beside a single cut.

744. Find Smallest Letter Greater Than Target​

744. Find Smallest Letter Greater Than Target

LeetCode
Easy

Upper Bound (Closed)

FIG. 744 FIND SMALLEST LETTER GREATER THAN TARGET CLOSED● INTERACTIVE
visualization loads as you reach it
class Solution:
def nextGreatestLetter(self, letters: list[str], target: str) -> str:
# Answers [0, len(letters)): never lands past the end, no match wraps to letters[0]
lo, hi = 0, len(letters) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if letters[mid] <= target:
lo = mid + 1
else:
hi = mid
return letters[lo] if letters[lo] > target else letters[0]
top ↑

436. Find Right Interval​

436. Find Right Interval

LeetCode
Medium

Binary Search the Sorted Starts

FIG. 436 FIND RIGHT INTERVAL● INTERACTIVE
visualization loads as you reach it
class Solution:
def findRightInterval(self, intervals: list[list[int]]) -> list[int]:
starts = sorted((i[0], idx) for idx, i in enumerate(intervals))
ans = []
for _, end in intervals:
# Answers [0, len(starts)): a real index, so post-check starts[lo][0] >= end
lo, hi = 0, len(starts) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if starts[mid][0] < end:
lo = mid + 1
else:
hi = mid
ans.append(starts[lo][1] if starts[lo][0] >= end else -1)
return ans
top ↑

2070. Most Beautiful Item for Each Query​

2070. Most Beautiful Item for Each Query

LeetCode
Medium

Prefix Max, Then Upper-Bound per Query

FIG. 2070 MOST BEAUTIFUL ITEM FOR EACH QUERY● INTERACTIVE
visualization loads as you reach it
class Solution:
def maximumBeauty(self, items: list[list[int]], queries: list[int]) -> list[int]:
items.sort(key=lambda i: (i[0], -i[1]))
for i in range(1, len(items)):
items[i][1] = max(items[i][1], items[i - 1][1])
ans = []
for q in queries:
# Answers [0, n]: lo can land on 0, so items[lo-1] is post-checked against q
lo, hi = 0, len(items)
while lo < hi:
mid = lo + (hi - lo) // 2
if items[mid][0] <= q:
lo = mid + 1
else:
hi = mid
best = items[lo - 1][1] if items[lo - 1][0] <= q else 0
ans.append(best)
return ans
top ↑

362. Design Hit Counter​

362. Design Hit Counter

LeetCode
Medium

Append, then Bisect the Window

FIG. DESIGN HIT COUNTER● INTERACTIVE
visualization loads as you reach it
class HitCounter:
def __init__(self):
self.hits = []
 
def hit(self, timestamp: int) -> None:
self.hits.append(timestamp)
 
def getHits(self, timestamp: int) -> int:
index = bisect.bisect_left(self.hits, timestamp - 300 + 1)
return len(self.hits) - index if 0 <= index < len(self.hits) else 0
top ↑

981. Time Based Key-Value Store​

981. Time Based Key-Value Store

LeetCode
Medium

Per-Key List, Bisect Right on Timestamp

FIG. 981 TIME BASED KEY VALUE STORE● 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
class TimeMap:
 
def __init__(self):
self.hashmap = collections.defaultdict(list)
 
def set(self, key: str, value: str, timestamp: int) -> None:
self.hashmap[key].append((value, timestamp))
 
def get(self, key: str, timestamp: int) -> str:
arr = self.hashmap[key]
idx = bisect_right(arr, timestamp, key=lambda x: x[1])
return arr[idx - 1][0] if idx > 0 else ""
top ↑

1146. Snapshot Array​

1146. Snapshot Array

LeetCode
Medium

Per-Index History, Bisect Right on snap_id

FIG. 1146 SNAPSHOT ARRAY● 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
 
 
class SnapshotArray:
 
def __init__(self, length: int):
self.arr = [[[0, 0]] for _ in range(length)]
self.snap_id = 0
 
def set(self, index: int, val: int) -> None:
if self.arr[index][-1][1] == self.snap_id:
self.arr[index][-1][0] = val
else:
self.arr[index].append([val, self.snap_id])
 
def snap(self) -> int:
self.snap_id += 1
return self.snap_id - 1
 
def get(self, index: int, snap_id: int) -> int:
idx = bisect_right(self.arr[index], snap_id, key=lambda x: x[1])
return self.arr[index][idx - 1][0]
top ↑

Two cuts, read the span​

Both cuts, then work with the [left, right) span between them.

34. Find First and Last Position of Element in Sorted Array​

34. Find First and Last Position of Element in Sorted Array

LeetCode
Medium

Bisect Boundaries

FIG. 34 FIND FIRST AND LAST POSITION OF ELEMENT IN SORTED ARRAY● 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
 
 
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
 
 
class Solution:
def searchRange(self, nums: list[int], target: int) -> list[int]:
left = bisect_left(nums, target)
if left == len(nums) or nums[left] != target:
return [-1, -1]
right = bisect_right(nums, target)
return [left, right - 1]
top ↑

2089. Find Target Indices After Sorting Array​

2089. Find Target Indices After Sorting Array

LeetCode
Easy

Bisect Boundaries

FIG. 2089 FIND TARGET INDICES AFTER SORTING ARRAY● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_left(self, arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] < target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
 
def bisect_right(self, arr, target, lo: int = 0, hi: int = None):
# hi is inclusive. The insert position of the new element can be at the end of the list with index=len(arr)
hi = hi or len(arr)
if lo == hi: # if array is empty
return -1
if arr[hi - 1] < target:
return hi
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] <= target:
lo = mid + 1
else:
hi = mid
return lo
def targetIndices(self, nums: List[int], target: int) -> List[int]:
nums = sorted(nums)
left = self.bisect_left(nums, target)
right = self.bisect_right(nums, target)
return list(range(left, right))
top ↑

1150. Check If a Number Is Majority Element in a Sorted Array​

1150. Check If a Number Is Majority Element in a Sorted Array

LeetCode
Easy

Bisect Boundaries

FIG. 1150 CHECK IF A NUMBER IS MAJORITY ELEMENT IN A SORTED ARRAY● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_left(self, arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] < target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
 
def bisect_right(self, arr, target, lo: int = 0, hi: int = None):
# hi is inclusive. The insert position of the new element can be at the end of the list with index=len(arr)
hi = hi or len(arr)
if lo == hi: # if array is empty
return -1
if arr[hi - 1] < target:
return hi
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] <= target:
lo = mid + 1
else:
hi = mid
return lo
def isMajorityElement(self, nums: List[int], target: int) -> bool:
left = self.bisect_left(nums, target)
right = self.bisect_right(nums, target)
count = right - left
return count > len(nums) / 2
top ↑

Element Occurrence​

Element Occurrence

Educative
Easy

Count via Boundaries

FIG. ELEMENT OCCURRENCE● INTERACTIVE
visualization loads as you reach it
def bisect_left(arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] < target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
 
 
def bisect_right(arr, target, lo: int = 0, hi: int = None):
# hi is inclusive. The insert position of the new element can be at the end of the list with index=len(arr)
hi = hi or len(arr)
if lo == hi: # if array is empty
return -1
if arr[hi - 1] < target:
return hi
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] <= target:
lo = mid + 1
else:
hi = mid
return lo
def findCount(nums: List[int], target: int):
left = bisect_left(nums, target)
right = bisect_right(nums, target)
count = right - left
return count if count != 0 else -1
top ↑

2529. Maximum Count of Positive Integer and Negative Integer​

2529. Maximum Count of Positive Integer and Negative Integer

LeetCode
Easy

Count Each Sign

FIG. 2529 MAXIMUM COUNT OF POSITIVE INTEGER AND NEGATIVE INTEGER COUNT● INTERACTIVE
visualization loads as you reach it
class Solution:
def maximumCount(self, nums: list[int]) -> int:
negatives = sum(num < 0 for num in nums)
positives = sum(num > 0 for num in nums)
return max(positives, negatives)
top ↑