4 of 5
Write a function search_insert(nums, target) that returns:
target if it exists in the sorted list, orYou can assume there are no duplicates.
print(search_insert([1, 3, 5, 6], 5)) # 2 (found at index 2) print(search_insert([1, 3, 5, 6], 2)) # 1 (insert between 1 and 3) print(search_insert([1, 3, 5, 6], 7)) # 4 (insert at end) print(search_insert([1, 3, 5, 6], 0)) # 0 (insert at start)
| Complexity | |
|---|---|
| Time | O(log n) |
| Space | O(1) |
This is binary search with a twist — instead of returning -1 on failure, return lo.
When the loop ends (lo > hi), lo is exactly the position where the target would go. Think about why:
lo up past midhi below midlo is sitting at the first value larger than target — the insertion pointdef search_insert(nums, target): pass print(search_insert([1, 3, 5, 6], 5)) # 2 print(search_insert([1, 3, 5, 6], 2)) # 1 print(search_insert([1, 3, 5, 6], 7)) # 4 print(search_insert([1, 3, 5, 6], 0)) # 0