19/29
Part 4 of 6 · Sorting and the latest entryLearn and do

bisect_right minus one does it in O(log n)

When you want O(log n), or an interviewer asks about scale, the bisect module does the search. Python's docs even ship this recipe, as a function called find_le.

from bisect import bisect_left, bisect_right

print(bisect_left([2, 5, 5, 7], 5), bisect_right([2, 5, 5, 7], 5))
Predict

What do bisect_left([2, 5, 5, 7], 5) and bisect_right([2, 5, 5, 7], 5) give?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

At t = -5, bisect_right(times, -5) is 0, so i is -1. Why does the code check i >= 0?

Pick one to see what it prints.
Pick an answer above to see the rest