How do you remove duplicates from a sorted array in place?
Use a slow pointer that tracks where the next unique value should be written, and a fast pointer that scans forward. Whenever the fast pointer finds a value different from the current unique one, copy it to the slow pointer's position and advance both. One pass, O(1) extra space.
How to think about it
Three words in the prompt do all the steering: sorted, in place, no extra space. Together they rule out the obvious answer — build a fresh list of uniques and copy it back — because that costs O(n) extra memory. The interviewer wants to see the slow/fast two-pointer pattern, sometimes called the read/write pointer, where you overwrite the array as you walk it.
The reason it works is the sort. Because the array is sorted, every copy of a value sits in one contiguous run, so a duplicate is just a value equal to the one before it. You keep a write head w at index 1 — the first element is always unique, so it stays put — and a read pointer r scanning from index 1 to the end. Each time nums[r] differs from nums[r-1], you have found the start of a new value: write it at w and push w forward. The function returns w, the length of the deduplicated prefix; whatever sits beyond it is leftover and ignored.
A worked example
def remove_duplicates(nums):
if not nums:
return 0
w = 1 # write head; index 0 is always unique
for r in range(1, len(nums)):
if nums[r] != nums[r - 1]:
nums[w] = nums[r]
w += 1
return w # length of the unique prefix
a = [1, 1, 2, 3, 3, 4]
k = remove_duplicates(a)
print(k, a[:k]) # the deduplicated prefix
b = [0, 0, 0, 0]
k = remove_duplicates(b)
print(k, b[:k]) # all identical -> one survivor
c = [1]
print(remove_duplicates(c)) # single element -> already unique
4 [1, 2, 3, 4]
1 [0]
1
Read the first result. The six-element input collapses to a prefix of length 4 holding [1, 2, 3, 4]. The read pointer skipped r=1 (a repeated 1) and r=4 (a repeated 3), writing only at the three points where the value changed — w ended at 4. The all-zeros case proves the floor: every element is a duplicate of the first, so exactly one survives and k is 1.