01
Problem Statement
Given a sorted array of distinct integers nums and a target value, return the index where target would be inserted to keep the array sorted. If target is already in nums, return its index. There are no duplicates.
- We need the lower bound of
target: the first indexisuch thatnums[i] >= target. That is exactly the insert position. Iftargetis larger than all elements, returnnums.length.
02
Key Observations
- This is the standard lower_bound (or leftmost position for
target): the smallest indexisuch thatnums[i] >= target. Use binary search with range[0, nums.length](so we can returnnif target is greater than all). Ifnums[mid] < target, we need to search the right half (left = mid + 1). Otherwisenums[mid] >= target, somidis a candidate and we search the left half (right = mid). Whenleft == right, we have the answer. - Loop condition
left < rightandright = mid(notmid - 1) so we don't skip the candidate.
03
Approach
High-level: Binary search for the first index i where nums[i] >= target. Search space [0, nums.length]. If nums[mid] < target, left = mid + 1; else right = mid. Return left.
Steps:
left = 0,right = nums.length. Whileleft < right:mid = left + (right - left) / 2. Ifnums[mid] < target,left = mid + 1; elseright = mid.- Return
left.
04
Implementation
Java
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
}
else {
right = mid;
}
}
return left;
}05
Test Cases
Example 1
Input
nums = [1,3,5,6], target = 5
Expected
2Explanation
5 found at 2.
06
Complexity Analysis
- Time: O(log n).
- Space: O(1).
07
Follow-ups
- Upper bound: first index where nums[i] > target.