Browse curriculum

Search Insert Position (LeetCode 35)

Search Insert Position (LeetCode 35): find where a target is, or where it would be inserted, in a sorted array with the lower-bound binary search template.

Problem Understanding

Search Insert Position: given a sorted array of distinct integers and a target, return the index of target if it is present, or the index where it would be inserted to keep the array sorted. It must run in O(log n).

Examples: in [1, 3, 5, 6], target 5 returns 2, target 2 returns 1, and target 7 returns 4.

The Intuition: One Question Covers Both Cases

"Where is it" and "where would it go" have the same answer: the first index whose value is ≥ target. If the target is present, that is its index; if not, it is the slot where it belongs.

Find that index with binary search over the half-open range [lo, hi):

  1. Start with lo = 0, hi = n, so "after everything" (index n) is a valid answer.
  2. Take mid. If nums[mid] < target, the answer is to the right: lo = mid + 1.
  3. Otherwise mid might be the answer, so keep it: hi = mid.
  4. When lo == hi, return lo.

This lower-bound loop is worth memorising: it never needs a special case for "found" and never goes out of bounds.

Search Insert Position Visualization

TARGET 5 · FIRST INDEX WITH VALUE ≥ TARGET

RANGE [0, n)

lo

1

0

3

1

5

2

6

3

hi

end

4

lo

0

hi

4

Answer

:

 

The answer is somewhere in [0, 4): index 4 means "after the last element"

Next

Range [0, 4): look at the middle, index 2, value 5

Free preview: the first 3 of 6 steps

nums

Target

Cells inside [lo, hi) are shaded, including the dashed slot for index n. Each step compares mid with the target and throws away half the range until lo and hi meet on the answer.

Search Insert Position Dry Run

Input: [1, 3, 5, 6], target = 2

lo hi mid nums[mid] Action
0 4 2 5 5 ≥ 2: hi = 2
0 2 1 3 3 ≥ 2: hi = 1
0 1 0 1 1 < 2: lo = 1
1 1 - - return 1

Search Insert Position LeetCode Solution

The lower-bound binary search over [0, n).

Search Insert Position Code
1var searchInsert = function(nums, target) {
2 let lo = 0, hi = nums.length;
3 while (lo < hi) {
4 const mid = (lo + hi) >> 1;
5 if (nums[mid] < target) lo = mid + 1;
6 else hi = mid;
7 }
8 return lo;
9};

Search Insert Position in Python, Java, C++, TypeScript and C

Search Insert Position in Python
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        lo, hi = 0, len(nums)
        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] < target:
                lo = mid + 1
            else:
                hi = mid
        return lo
Search Insert Position in Java
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;
    }
}
Search Insert Position in C++
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int lo = 0, hi = nums.size();
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] < target) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
};
Search Insert Position in TypeScript
function searchInsert(nums: number[], target: number): number {
    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;
}
Search Insert Position in C
int searchInsert(int* nums, int numsSize, int target) {
    int lo = 0, hi = numsSize;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (nums[mid] < target) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

Edge Cases & Common Mistakes

  • Target larger than everything: the answer is n; starting with hi = n − 1 would miss it.
  • Target smaller than everything: the answer is 0.
  • hi = mid − 1: that can skip the very index you are looking for.
  • Overflow in other languages: compute mid as lo + (hi − lo) / 2 where integers are fixed-width.

Summary

Both questions, where the target is and where it would go, ask for the first index with a value ≥ target. Binary search the half-open range [0, n): move lo past values that are too small, pull hi down onto values that are big enough, and return lo. O(log n) time, O(1) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Search [0, n)

    Set lo = 0 and hi = len(nums), so the 'after the end' position is included.

  2. Halve the range

    While lo < hi, take mid. If nums[mid] < target, set lo = mid + 1; otherwise set hi = mid.

  3. Return lo

    When lo == hi, it is the first index with a value ≥ target: where target is, or where it belongs.

Frequently asked questions

Why is hi set to len(nums) instead of len(nums) − 1?

The answer can be len(nums), when the target is larger than every element. Searching the half-open range [0, n) keeps that index in play, and the loop ends exactly when lo == hi.


Why hi = mid and not hi = mid − 1?

If nums[mid] ≥ target, mid itself might be the first such index, so it must stay in the range. Only when nums[mid] < target is mid ruled out, which is why that branch sets lo = mid + 1.


What is this template called?

It is lower bound: the first position whose value is not less than the target, the same as bisect_left in Python and std::lower_bound in C++. The same loop solves many binary search problems once you know what to compare.

New to the technique behind this problem? Watch it run step by step:

Binary Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description