Search Insert Position
LeetCode 35 · Easy · solution, intuition & step-by-step walkthrough
When the search fails, low is the insert position.
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
Binary search for target.
- 2
Found → return mid.
- 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 lowSearch 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.