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
This is a classic lower bound binary search. We want the first index where nums[i] >= target.
If the target exists, that search lands on its first position. If the target does not exist, that same position is exactly where it should be inserted.
When the loop ends, left is the correct answer. It works whether the target is already present or not.
This solution takes O(log n) time and O(1) extra space.
Best Answers
class Solution {
public int search_insert(Object nums, Object target) {
int[] arr = (int[]) nums;
int t = (int) target;
int left = 0;
int right = arr.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < t) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
