35. Search Insert Position¶
Edited by Charles
Easy · Python · Array
Problem
Read the original problem on LeetCode.
The official page contains the problem statement, examples, and constraints.
Explanation, examples & other approaches
Core idea
Use Binary Search.
If target exists in the sorted array, return its index.
Original study notes follow, including intermediate snippets and earlier attempts.
Idea¶
Use Binary Search.
If target exists in the sorted array, return its index.
If target does not exist, return the position where it should be inserted so that the array remains sorted.
Binary Search¶
Initialize:
The current search interval is:
Calculate:
There are three cases.
Case 1: nums[mid] == target¶
We found the target:
Case 2: nums[mid] > target¶
Since the array is sorted, target must be on the left side of mid.
Case 3: nums[mid] < target¶
target must be on the right side of mid.
Why Return left?¶
If target does not exist, binary search eventually ends when:
At this point:
left is exactly the position where target should be inserted.
Another way to understand it:
During binary search:
left keeps moving past elements that are definitely smaller than target.
Therefore, when the search finishes, left is the first position where target can be inserted.
Example¶
Initially:
Round 1¶
Since:
move right:
Round 2¶
Since:
move left:
Now:
Therefore:
2 should be inserted between 1 and 3, so:
Boundary Cases¶
If target is smaller than every element:
Insert at the beginning.
If target is larger than every element:
Insert at the end.
Thus, return left naturally handles all insertion positions.
Complexity¶
Time Complexity:
The search interval is reduced by half after each iteration.
Space Complexity:
Only a few variables are used.
Key Points¶
Binary search interval:
Update rules:
nums[mid] > target
→ target is on the left
→ right = mid - 1
nums[mid] < target
→ target is on the right
→ left = mid + 1
If the target is not found:
Therefore:
Key intuition: left keeps moving past elements that are definitely smaller than target. When binary search finishes, left is exactly where target should be inserted.
Study record
| Field | Value |
|---|---|
| Attempts | 1 |
| Mastery | ❚ |
| The Latest Attempt | September 8, 2026 |
Python solution¶
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
mid = (left + right) // 2
while left <= right:
if nums[mid] == target:
return mid
if nums[mid] > target:
right = mid - 1
else:
left = mid + 1
mid = (left + right) // 2
return left