The problem, in one line. Given a sorted list of distinct numbers and a target, return the position of the target, or the position where it would have to be inserted to keep the list sorted. LeetCode 35.
The tell. A sorted list and a question about a position, not about whether a value exists. When the answer is “the first place where the condition turns true”, search for that boundary.
The wrong first idea
Walk from the left and stop at the first number that is not smaller than the target.
for i, x in enumerate(nums):
if x >= target:
return i
return len(nums)
Correct, and it handles all the edges. It costs one look per number, so a million numbers can cost a million looks, and the sorted order is never used.
The invariant
Search for the first position whose number is at least the target. Let hi start one past the end, because “insert at the very end” is a legal answer.
flowchart LR A["lo 0, hi 5<br/>mid 2 holds 5<br/>5 >= 2, hi = 2"] --> B["lo 0, hi 2<br/>mid 1 holds 3<br/>3 >= 2, hi = 1"] B --> C["lo 0, hi 1<br/>mid 0 holds 1<br/>1 < 2, lo = 1"] C --> D["lo = hi = 1<br/>answer 1"]
The sentence that stays true every step: everything left of lo is smaller than the target, and the number at hi (or the end) is not. When the two meet, that meeting point is the answer, found or not.
The solution
def search_insert(nums, target):
lo, hi = 0, len(nums) # hi may equal len(nums): insert at the end
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target:
lo = mid + 1 # mid is too small, the spot is further right
else:
hi = mid # mid could be the spot, keep it
return lo
print(search_insert([1, 3, 5, 6, 8], 5))
print(search_insert([1, 3, 5, 6, 8], 2))
print(search_insert([1, 3, 5, 6, 8], 9))
2
1
5
func searchInsert(nums []int, target int) int {
lo, hi := 0, len(nums) // hi may equal len(nums): insert at the end
for lo < hi {
mid := lo + (hi-lo)/2
if nums[mid] < target {
lo = mid + 1 // mid is too small, the spot is further right
} else {
hi = mid // mid could be the spot, keep it
}
}
return lo
}
Same three calls print 2, 1, 5.
Complexity
- Time O(log n): the range between
loandhihalves every loop. - Space O(1): two indexes and the middle.
Traps
- Starting
hiatlen(nums) - 1. A target bigger than everything, like 9 above, then answers 4 when the right answer is 5. - Writing
hi = mid - 1with thelo < hitest. On[1, 3]with target 2 it answers 0 when the right answer is 1. - Returning -1 for a miss because the last problem did. Here a miss is a normal answer, and it is the whole point.
Next in the ladder
Search a 2D Matrix gives you a grid instead of a list. The trick is noticing that the grid, read row by row, is one long sorted list.