progress

~/problems / Binary search / Binary search

Search Insert Position

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~12 min

A leaderboard keeps distinct scores in increasing order. Write slot_for(nums: list[int], target: int) -> int that returns target's index, or the index where it would 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
  • len(nums) <= 10^6. No list.index, in, or bisect: write the loop.
  • ⭐ Bonus: a speed test with many calls earns a star at O(log n) per call.
  • C++ / Java: write slotForAll(nums, targets), returning the answer for each target (call a slotFor helper in a loop).
Show hint

you want the first index whose value is at least target (maybe len(nums)). Keep a range that contains it and halve it.

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

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