I would like to use binary search on a SortedList
with a key function, e.g. similarly to bisect_right()
in the bisect
module. However, SortedList.bisect_right()
only supports searching by value. How to make it work with a key function?
How to use binary search on an existing SortedList with a key function?
169 Views Asked by Eugene Yarmash At
2
There are 2 best solutions below
1

You specify the key
for a SortedList
in its constructor.
https://grantjenks.com/docs/sortedcontainers/sortedlist.html#sortedcontainers.SortedList
The SortedList
is sorted according to that key, and the bisect
methods in SortedList
necessarily use the same key, since bisection requires an understanding of how the list is sorted.
If you have a
SortedList
already and it's sorted by the given key, you can usebisect.bisect_right
on that, e.g.:If you need to search repeatedly, it would be more efficient to create a
SortedKeyList
and use itsbisect_key_right()
method. The extra efficiency comes from not indexing the sorted list during a binary search, as that itself is aO(log(n))
operation.