~/problems / Binary search / Binary search

Search Insert Position

easy ~12 min

A leaderboard keeps its distinct scores in a strictly increasing list. Write slot_for(nums: list[int], target: int) -> int:

  • if target is in nums, return its index;
  • otherwise return the index where it would have to be inserted to keep nums sorted.
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 the bisect module; write the loop yourself.
  • C++ / Java: you write slotForAll(nums, targets), which returns slotFor(nums, t) for every t in targets, in order, so the tests can run many searches on one big list. Write slotFor as 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.

Topic: Binary search. lo/hi invariants, lower vs upper bound, rotated arrays, bisect.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc