Search Insert Position

Easy

Topics
ArrayBinary Search

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

103152found63
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

1031insert here5263
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

  1. Search a half-open range [lo, hi) with hi = n.
  2. If nums[mid] < target, the answer is strictly right: lo = mid + 1.
  3. Otherwise mid is a candidate: hi = mid.
  4. When the range collapses, lo is 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 1

Complexity

  • Time — O(log n): binary search halves the range.
  • Space — O(1): two indices.

Common Pitfalls

  • hi starts at len(nums), one past the end, not len(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 < hi with hi = mid, so it converges on a boundary rather than searching for an exact hit. Mixing this with hi = mid - 1 is 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 lo
SensAI
Beta
Tap the mic to stop voice mode