Squeeze the duplicates out of a sorted array in place: a read pointer scans ahead while a write pointer keeps each new value.
▼The problem
LeetCode 26 (Easy). nums is sorted in non-decreasing order. Remove the duplicates in place so each unique value appears once, keeping the order, and return k, the number of unique values; the first k slots must hold them (whatever is after slot k - 1 doesn't matter).
Example (LeetCode's second): [0,0,1,1,1,2,2,3,3,4] → k = 5, first five slots 0 1 2 3 4 (afterwards the array is [0,1,2,3,4,2,2,3,3,4]).
The solution
def removeDuplicates(nums):
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[write - 1]:
nums[write] = nums[read]
write += 1
return writeTranscript
Remove Duplicates from Sorted Array. You get a list of numbers, sorted from small to large, and some repeat. Keep one copy of each value, in order, inside the same array. Then return k, the number of unique values. The first k slots must hold them; whatever comes after doesn't matter.
Take zero, zero, one, one, one, two, two, three, three, four. Five different values, so k is five, and the first five slots should read zero, one, two, three, four.
The obvious way deletes each repeat and shifts everything after it one slot to the left. The extra zero moves eight numbers. The extra ones move six, then five. On this short list that's already twenty-three moves, and a long run of repeats makes it n squared. Copying into a new list is quick, but it isn't in place.
Here's the trick: two pointers. Read moves fast, visiting every slot once. Write moves slowly, marking where the next new value belongs. Because the list is sorted, equal values sit side by side. So a value is new exactly when it differs from the last value we kept. One comparison per slot is enough.
In code, write starts at one, because the first value is always kept. Read loops from one to the end. If the value at read differs from the value just before write, copy it over to write, and move write one step right. When the loop ends, return write.
Let's walk it. Zero matches zero: skip. One is new: copy it to slot one. The next two ones match: skip, skip. Two is new: it goes to slot two. Skip the second two. Three goes to slot three, skip its twin, and four lands in slot four. Write ends at five, so k is five.
Read passes once, so the time is order n. Just two pointers, no extra list, so the extra space is order one.
Read fast, write slow, keep the first of each. That's Remove Duplicates from Sorted Array.