Search Insert Position
Easy
Topics
Given a sorted array of distinct integers nums and a target, return the index if found. If not, return the index where it would be inserted to keep the array sorted. O(log n).
Example 1
Target 5 is already present at index 2.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [1,3,5,6], target = 5 Output: 2
Example 2
Target 2 is absent, and the answer is where it would go: index 1.
Input: nums = [1,3,5,6], target = 2 Output: 1
Constraints
- 1 <= nums.length <= 10^4
- nums is sorted ascending with distinct values.
Editorial — intuition, approach, complexity and pitfalls
Intuition
This is the "lower bound" flavor of binary search: find the first index whose value is ≥ target. If the target is present that is its index; otherwise it is the correct insertion point.
Approach
- Search a half-open range
[lo, hi)withhi = n. - If
nums[mid] < target, the answer is strictly right:lo = mid + 1. - Otherwise
midis a candidate:hi = mid. - When the range collapses,
lois the answer.
Walkthrough
nums = [1,3,5,6], target = 2
lo=0 hi=4 mid=2 (5) >=2 -> hi=2
lo=0 hi=2 mid=1 (3) >=2 -> hi=1
lo=0 hi=1 mid=0 (1) <2 -> lo=1
lo==hi==1 -> insert at 1Complexity
- Time — O(log n): binary search halves the range.
- Space — O(1): two indices.
Common Pitfalls
histarts atlen(nums), one past the end, notlen(nums) - 1. The answer may be the insert position *after* the last element, and a high bound of the last index cannot represent it: a target larger than everything returns 3 instead of 4 on a four-element array.- The loop is
lo < hiwithhi = mid, so it converges on a boundary rather than searching for an exact hit. Mixing this withhi = mid - 1is how the off-by-one creeps in.
Full Solution — all languages
class Solution:
def searchInsert(self, nums, target):
lo, hi = 0, len(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return loimport java.util.*;
class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int searchInsert(vector<int>& nums, int target) {
int lo = 0, hi = (int)nums.size();
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var searchInsert = function(nums, target) {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
};