The machine must remove duplicates in place from a sorted array and return the new length k; the first k slots must hold the unique values, in order. The insight: since the array is sorted, a slow pointer marks where the next unique value belongs, and a fast pointer finds it. Write, don't delete — overwriting is cheaper than shifting.
def remove_duplicates(nums):
if not nums:
return 0
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[read - 1]:
nums[write] = nums[read]
write += 1
return writeSteps: (1) keep a write pointer starting at 1, (2) scan with a read pointer, (3) when a value differs from its predecessor, copy it to the write position and advance.
Time is O(n), one pass. Space is O(1) — in place, no auxiliary array.
Trickiest edge cases: an empty array returns 0 before any pointer moves. A single element returns 1. All-identical input like [5,5,5] returns 1 with the first slot unchanged. The comparison is against nums[read - 1] (the previous element), not against the last written value — both work on sorted input, but the read-1 variant is immune to write/read skew bugs.