Where to Insert a Value in a Sorted Array
Problem
Given a sorted array of distinct integers and a target, return the index where the target is found, or the index where it would be inserted to keep the array sorted.
Standard lower-bound binary search: maintain [lo, hi). While lo < hi, look at mid: if nums[mid] < target, push lo to mid + 1; else pull hi to mid. The final lo is the smallest index whose value is ≥ target — exactly the insertion point.
Input
nums = [1, 3, 5, 6], target = 5Output
2Target 5 sits at index 2. For target 4 the answer would be 2 (insert before 5); for 7 it's 4 (append).
def search_insert(nums, target):
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target: lo = mid + 1
else: hi = mid
return lo
function searchInsert(nums, target) {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
int searchInsert(vector<int>& nums, int target) {
int lo = 0, hi = (int)nums.size();
while (lo < hi) {
int mid = (lo + hi) / 2;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}