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.
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
Upper Bound (Closed)
FIG. 744 FIND SMALLEST LETTER GREATER THAN TARGET CLOSED● INTERACTIVE
visualization loads as you reach it
436. Find Right Interval
436. Find Right Interval
Binary Search the Sorted Starts
FIG. 436 FIND RIGHT INTERVAL● INTERACTIVE
visualization loads as you reach it
2070. Most Beautiful Item for Each Query
2070. Most Beautiful Item for Each Query
Prefix Max, Then Upper-Bound per Query
FIG. 2070 MOST BEAUTIFUL ITEM FOR EACH QUERY● INTERACTIVE
visualization loads as you reach it
362. Design Hit Counter
362. Design Hit Counter
Append, then Bisect the WindowO(log N) timeO(N) aux
Queue of TimestampsO(n) timeO(n) aux
Queue of (Timestamp, Count) PairsO(n) timeO(n) aux
Circular BufferO(300) time best timeO(2*300) aux best space
Append, then Bisect the Window
FIG. DESIGN HIT COUNTER● INTERACTIVE
visualization loads as you reach it
981. Time Based Key-Value Store
981. Time Based Key-Value Store
Per-Key List, Bisect Right on Timestamp
FIG. 981 TIME BASED KEY VALUE STORE● INTERACTIVE
visualization loads as you reach it
1146. Snapshot Array
1146. Snapshot Array
Per-Index History, Bisect Right on snap_id
FIG. 1146 SNAPSHOT ARRAY● INTERACTIVE
visualization loads as you reach it
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
Bisect Boundaries
FIG. 34 FIND FIRST AND LAST POSITION OF ELEMENT IN SORTED ARRAY● INTERACTIVE
visualization loads as you reach it
2089. Find Target Indices After Sorting Array
2089. Find Target Indices After Sorting Array
Bisect Boundaries
FIG. 2089 FIND TARGET INDICES AFTER SORTING ARRAY● INTERACTIVE
visualization loads as you reach it
1150. Check If a Number Is Majority Element in a Sorted Array
1150. Check If a Number Is Majority Element in a Sorted Array
Bisect Boundaries
FIG. 1150 CHECK IF A NUMBER IS MAJORITY ELEMENT IN A SORTED ARRAY● INTERACTIVE
visualization loads as you reach it
Element Occurrence
Element Occurrence
Count via Boundaries
FIG. ELEMENT OCCURRENCE● INTERACTIVE
visualization loads as you reach it