Search Insert Position
You're given an array nums of distinct integers sorted in ascending order, and an integer target. If target is in nums, return its index. If it isn't, return the index where it would be inserted to keep nums sorted, which can be anywhere from 0 to nums.length. Your solution must run in O(log n) time.
Examples
nums = [1,3,5,6], target = 5 returns 2
5 is already in the array, at index 2.
nums = [1,3,5,6], target = 2 returns 1
2 is missing. It belongs between 1 and 3, so it would go at index 1.
nums = [1,3,5,6], target = 7 returns 4
7 is larger than every value, so it would go at the end, index 4, which equals the array's length.
Constraints
- 1 <= nums.length <= 10^4
- -10^4 <= nums[i], target <= 10^4
- nums contains distinct values sorted in ascending order.
Hints
Whether or not target is present, what property does the answer's position have in terms of the values around it?
Binary search for the first index whose value is greater than or equal to target.
Set lo = 0 and hi = len(nums). While lo < hi, take mid; if nums[mid] < target set lo = mid + 1, else set hi = mid. Return lo.
Drill This: Your Approach First
Approach
Both cases ask for the same index: the first position whose value is at least target. Binary search for it over the half-open range lo = 0, hi = n. If nums[mid] < target, the answer is to the right of mid, so lo = mid + 1; otherwise mid itself could be the answer, so hi = mid. When lo meets hi, it is the answer. Starting hi at n lets the search return the end position.
Time
O(log n)
Space
O(1)
Pitfall
Solutions
class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
}class Solution:
def searchInsert(self, nums, target: int) -> int:
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo