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
Example 4:
Input: nums = [1,3,5,6], target = 0
Output: 0
To achieve the O(log n) runtime complexity, we can use a binary search approach. Here’s the strategy in detail:
left at the beginning (0) and right at the end (len(nums) - 1) of the array.middle index.nums[middle] is equal to the target, return middle.nums[middle] is less than the target, move the left pointer to middle + 1 to search in the right subarray.nums[middle] is greater than the target, move the right pointer to middle - 1 to search in the left subarray.left pointer will indicate the correct insertion position.def search_insert(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
This approach ensures efficient and correct insertion/index location of the target in the sorted array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?