Search Insert Position — LeetCode 35 Python Solution
- Problem
- #35
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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 lComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log n) |
| Space | O(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.