Search Insert Position easy
Problem Statement
Given a sorted array of distinct integers nums
and an integer target
, 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
Steps
-
Binary Search: Since the array is sorted, we can employ a binary search algorithm. This algorithm efficiently searches for a target value within a sorted array.
-
Initialization: Set
left
pointer to 0 andright
pointer tolen(nums) - 1
. -
Iteration: While
left
is less than or equal toright
:- Calculate the
mid
index:mid = (left + right) // 2
. Integer division is crucial here. - Comparison:
- If
nums[mid] == target
: The target is found, returnmid
. - If
nums[mid] < target
: The target is in the right half, so updateleft = mid + 1
. - If
nums[mid] > target
: The target is in the left half, so updateright = mid - 1
.
- If
- Calculate the
-
Target Not Found: If the loop completes without finding the target, it means the target needs to be inserted. The
left
pointer will now point to the index where the target should be inserted. Returnleft
.
Explanation
The binary search repeatedly halves the search space. This ensures a logarithmic time complexity. When the target is not found, the left
pointer converges to the correct insertion point. Consider Example 2:
- Initially,
left = 0
,right = 3
. mid = 1
,nums[mid] = 3
. Since3 > 2
,right
becomes 0.left = 0
,right = 0
.mid = 0
,nums[mid] = 1
. Since1 < 2
,left = 1
.- The loop terminates because
left (1) > right (0)
. The function returnsleft
, which is 1, the correct insertion point.
Code
def searchInsert(nums, target):
"""
Finds the index of the target in a sorted array, or the insertion index if not found.
Args:
nums: A sorted list of integers.
target: The integer to search for.
Returns:
The index of the target, or the insertion index.
"""
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
Complexity
- Time Complexity: O(log n) due to the binary search.
- Space Complexity: O(1). The algorithm uses a constant amount of extra space.