Problem Statement
Remove Duplicates from Sorted Array
You are given a list of whole numbers called nums. It is already sorted, meaning the numbers go from smallest to largest with no number ever going backward. Some numbers repeat. Your job is to keep only one copy of each number and push all the unique numbers to the front of the same list, still in order. You then return k, the count of how many unique numbers there are. "In-place" means you are not allowed to build a brand new list, you have to rearrange this one. The spots after the first k numbers do not matter, they can hold anything.
Translate the prompt
Remove duplicates from a sorted array in-place and return the count of distinct values. Only the first `count` positions need to be correct; anything after is ignored.
Signals to notice
Brute force first
Copy uniques into a new array, then copy back. O(n) time but O(n) extra space and defeats the in-place requirement.
The key insight
Because the array is sorted, duplicates are always adjacent. "New value" is equivalent to "different from the previous element" — a O(1) local test, not a O(n) search.
Trace it on nums=[1,1,2,2,3]
start w=1 r=1 nums[1]=1 == nums[0]=1 skip r=2 nums[2]=2 != nums[1]=1 write → [1,2,2,2,3] w=2 r=3 nums[3]=2 == nums[2]=2 skip r=4 nums[4]=3 != nums[3]=2 write → [1,2,3,2,3] w=3 return 3
What must stay true
At every iteration, `nums[0..write)` is the sorted list of distinct values seen in `nums[0..read]`.
Shape of the loop
if n == 0: return 0
w = 1
for r in 1..n-1:
if nums[r] != nums[r-1]:
nums[w] = nums[r]
w += 1
return wPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Forgetting that `write=0` means element 0 is already "kept", so `write` should start at 1. Starting at 0 double-counts the first value.