Tensorum
LeetCode 35 · Basics / Lower & Upper Bound

Search Insert Position

LeetCode 35 · Easy · solution, intuition & step-by-step walkthrough

When the search fails, low is the insert position.

EasyArrayBinary Search
0 msruntime · beats 100%
18.3 MBmemory · beats 100%
1approach
5accepted runs · last 23 Apr 2025

This is how I solved Search Insert Position (LeetCode 35), an easy problem from the Basics / Lower & Upper Bound pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Standard binary search, with one extra observation: if the target isn't present, the loop ends with low pointing at the first element larger than the target — exactly where it should be inserted.

Approach

  1. 1

    Binary search for target.

  2. 2

    Found → return mid.

  3. 3

    Not found → return low.

How I solved it

Binary search (lower bound)PythonO(log n) time
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        low = 0
        high= len(nums)-1
        while low<=high:
            mid = (low+high)//2
            if nums[mid]==target:
                return mid
            if nums[mid]>=target:
                high=mid-1
            else:
                low=mid+1
        return low
Loading the step-through…

Search Insert Position — FAQ

What is the intuition behind Search Insert Position?

Standard binary search, with one extra observation: if the target isn't present, the loop ends with low pointing at the first element larger than the target — exactly where it should be inserted.

How do you solve Search Insert Position (LeetCode 35)?

1. Binary search for target. 2. Found → return mid. 3. Not found → return low.

What is the time and space complexity of Search Insert Position?

Time: O(log n). Space: O(1). (Accepted approach: Binary search (lower bound).)

What are common mistakes in Search Insert Position?

Returning high would give the index before the insert slot.