Search insert position
Easy TimeO(log n) SpaceO(1)
Given a sorted array nums of distinct values and a target, return the index where the target is — or, when it is absent, the index it would have to take for the array to stay sorted. A target below everything belongs at 0, and one above everything belongs one past the last index.
Examples
Example 1
- Input
- nums = [1, 3, 5, 6]target = 4
- Output
- 4 is missing, and belongs between the
23and the5— at index 2.
Example 2
- Input
- nums = [1, 3, 5, 6]target = 7
- Output
- 7 is above everything, so it belongs at index 4, one past the last.
4
The Code
function searchInsert(nums, target) {
let low = 0;
let high = nums.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (nums[mid] < target) low = mid + 1;
else high = mid;
}
return low;
}
searchInsert([1, 3, 5, 6], 4);Done
More like this
All searching examples (8) →- Binary search Halve the search range each step with lo / mid / hi.
- Linear search Scan left to right until you find the value.
- Rotated search Binary search where one half is always sorted — use it.
- Find peak Climb toward the higher neighbour — a peak must lie that way.
- Binary search (recursive) The same halving, written as a call tree instead of a loop.
- Search on the answer Binary search the answer space, not the array.