Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5 Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2 Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7 Output: 4
Constraints:
1 <= nums.length <= 104-104 <= nums[i] <= 104nums contains distinct values sorted in ascending order.-104 <= target <= 104When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are holding a numbered item and need to place it into a sorted lineup of items in its proper spot. The brute force strategy involves examining the lineup step by step from the very beginning to find the exact place where your item belongs.
Here's how the algorithm would work step-by-step:
def search_insert_position(sorted_numbers, target_value):
# Scan sequentially to find the first element that is not smaller than our target
for current_index in range(len(sorted_numbers)):
if sorted_numbers[current_index] >= target_value:
return current_index
# If no larger element exists, the target must be placed at the very end
return len(sorted_numbers)Instead of scanning through every single item one by one, we can use a clever narrowing strategy similar to looking up a word in a dictionary. By repeatedly checking the middle of our current options and throwing away the half we do not need, we can home in on the correct spot almost instantly.
Here's how the algorithm would work step-by-step:
def search_insert(sorted_items, target_item):
left_bound = 0
right_bound = len(sorted_items) - 1
while left_bound <= right_bound:
middle_index = left_bound + (right_bound - left_bound) // 2
middle_item = sorted_items[middle_index]
# Exact match found, so this middle index is the correct position.
if middle_item == target_item:
return middle_index
# Target is larger, so we eliminate the left half and current middle.
elif middle_item < target_item:
left_bound = middle_index + 1
# Target is smaller, so we eliminate the right half and current middle.
else:
right_bound = middle_index - 1
# The search space is exhausted, and left_bound marks the insertion point.
return left_bound| Case | How to Handle |
|---|---|
| Target is smaller than all elements in the array | Binary search will narrow down to index zero, returning it as the correct insertion position. |
| Target is larger than all elements in the array | Binary search pointers will cross and the left pointer will naturally point to the array length. |
| Array contains only a single element | The binary search logic compares the target against this single element and returns either zero or one correctly. |
| Target matches an element in the middle of the array | Binary search finds the exact match and immediately returns its current index. |
| Array contains negative numbers and zeros alongside positive integers | Standard numerical comparisons in binary search handle negative and positive number ranges without modification. |
| Maximum sized arrays approaching memory or performance limits | The logarithmic time complexity ensures the search executes efficiently well within standard time limits. |
| Integer overflow during mid-index calculation | Calculating the midpoint using low plus high minus low divided by two prevents potential integer overflow. |