Problem Statement
Search Insert Position
You are given a list of numbers that is already sorted from smallest to largest, with no repeats. You are also given a target number. If the target is in the list, return the spot (the index) where it sits. If it is not in the list, return the spot where it would go to keep the list sorted. One catch: your method has to run in O(log n) time, which means it has to get much faster than checking every item one by one.
Signals to notice
Brute force first
Scan linearly to find the position. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
The key insight
Binary search: narrow the range by half each step. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on nums=[1,3,5,6], target=2
init: left=0, right=3 mid=(0+3)//2=1, nums[1]=3 > 2 -> right=mid-1=0; now left=0,right=0 mid=(0+0)//2=0, nums[0]=1 < 2 -> left=mid+1=1; now left=1,right=0 left=1 > right=0 -> while left<=right fails, exit loop target not found; return left=1 (insertion index, matches expected output 1)
What must stay true
The left pointer always points to the correct insertion position when search ends. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
# narrow toward target; return on exact hit
if found: return mid
elif too small: move left up
else: move right down
return left # left = insertion point when not foundPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Off-by-one in the return value — return left, not mid, when the target isn't found. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.