15/41
Part 3 of 7 · bisectLearn and do

Read an insertion point as a count, and most lookups take one line

The name says where you'd insert x. Read it instead as a count. The table uses a half-open range, written [start, end): it includes its start and leaves out its end. That's the usual way to state a time range. [start, end] includes both ends. Its last column runs each line on a = [100, 130, 130, 130, 220, 300], with x = 130, a range from 130 to 300, and 200 for the last row.

QuestionExpressionResult
How many are less than xbisect_left(a, x)1
How many are at most xbisect_right(a, x)4
The latest at or before xa[bisect_right(a, x) - 1]130, index 3
The latest strictly before xa[bisect_left(a, x) - 1]100, index 0
The earliest at or after xa[bisect_left(a, x)]130, index 1
How many in [start, end)bisect_left(a, end) - bisect_left(a, start)4
How many in [start, end]bisect_right(a, end) - bisect_left(a, start)5
Is x therei = bisect_left(a, x), then i < len(a) and a[i] == xFalse

Pick the pair by asking what a value equal to an end should do. The half-open range uses bisect_left at both ends:

RangeBoundsCount
[130, 300): 130 counts, 300 doesn'tbisect_left at both ends: 1 and 55 - 1 = 4
[130, 300]: both ends countbisect_right at the end: 1 and 66 - 1 = 5

The three lookups that index into the list need an edge check every time: the index must be at least 0 and below len(a). Subtracting 1 can give -1, and the earliest at or after can be len(a), one past the last index.

In the editor, write changes_between(times, start, end), a count over a half-open range. It prints the changes from 130 up to 200, and a range that ends before it starts.