A leaderboard keeps its distinct scores in a strictly increasing list. Write slot_for(nums: list[int], target: int) -> int:
- if
targetis innums, return its index; - otherwise return the index where it would have to be inserted to keep
numssorted.
slot_for([2, 6, 9, 14], 9) # 2
slot_for([2, 6, 9, 14], 7) # 2 (between 6 and 9)
slot_for([2, 6, 9, 14], 1) # 0
slot_for([2, 6, 9, 14], 20) # 4
slot_for([], 5) # 0
0 <= len(nums) <= 10^6; values are distinct and in[-10^9, 10^9].- The tests make thousands of calls on one big list, so each call must be O(log n). Don't use
list.index,in, or thebisectmodule; write the loop yourself. - C++ / Java: you write
slotForAll(nums, targets), which returnsslotFor(nums, t)for everytintargets, in order, so the tests can run many searches on one big list. WriteslotForas a helper and call it in a loop.
Show hint
you're looking for the first index whose value is at least target. Keep a range that is sure to contain that index (it may be len(nums)) and halve it each step.