Search Insert Position
You are given a sorted array and a target value. If the target already exists, return its index. If it does not exist, return the index where it should be inserted so the array would still stay sorted.
That means the answer is the first position where the target could fit without breaking the order. Sometimes that position is in the middle, and sometimes it is all the way at the front or the end.
For example, if nums = [1,3,5,6] and target = 5, the answer is 2 because 5 is already there. If target = 2, the answer is 1 because 2 should go between 1 and 3. If target = 7, the answer is 4 because it belongs after the last value.
So the task is to find the first index where the value is greater than or equal to the target.
Example Input & Output
The number 5 already exists in the list and is located at index 2.
The target 2 is not in the list but would fit between 1 and 3, so its position would be index 1.
The target 7 is greater than all elements, so it should appear at the end, which corresponds to index 4.
Algorithm Flow
Solution Approach
Find the index where a target value should be inserted in a sorted array to maintain order. Use binary search. Maintain left and right bounds. At each step, compute mid. If nums[mid] equals target, return mid. If nums[mid] is less than target, search right half. Otherwise, search left half. When the loop ends, left is the insertion position.
Binary search narrows the range. When the target is not found, left points to the first element greater than target, which is the correct insertion index.
Time complexity is O(log n), space complexity is O(1).
Best Answers
class Solution {
public int search_insert(int[] nums, int target) {
int left = 0;
int right = nums.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
