Search Insert Position — LeetCode 35 Python Solution

EasyArrayBinary Search
Problem
#35
Reading time
2 min

The problem

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

Example

Input
nums = [1,3,5,6], target = 5
Output
2

Python solution

Python
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        l, r = 0, len(nums)
        while l < r:
            mid = (l + r) >> 1
            if nums[mid] >= target:
                r = mid
            else:
                l = mid + 1
        return l

Complexity

MeasureComplexity
TimeO(\log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 35. Search Insert Position is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 35. Search Insert Position?
LeetCode 35. Search Insert Position is rated Easy on LeetCode.
What is the time complexity of LeetCode 35. Search Insert Position?
The Python solution on this page runs in O(\log n).
What is the space complexity of LeetCode 35. Search Insert Position?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 35. Search Insert Position cover?
LeetCode 35. Search Insert Position is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview