Remove Duplicates from Sorted Array
Given a sorted array, remove duplicates in place so each value appears once. Return the new length k; the first k slots must hold the unique values.
Intuition
Because the array is sorted, duplicates sit next to each other. A slow pointer marks the end of the unique prefix; a fast pointer scans ahead and, whenever it finds a new value, we extend the prefix.
Approach
The easy version uses extra space
You could collect the unique values into a new list and copy them back, but the problem demands an in-place solution with O(1) extra space. The one fact that makes in-place possible is that the array is sorted, so any duplicates are adjacent — we never have to look far to detect them.
Separate a 'read' pointer from a 'write' pointer
Keep a slow write pointer l marking the last slot of the unique prefix we've built, and a fast read pointer k scanning ahead. Because duplicates are adjacent, a value is new exactly when it differs from nums[l] (the last value we kept). When k finds such a new value, we advance l and copy it into place — overwriting a duplicate we no longer need.
Walk once; the length is l + 1
Start l = 0 (the first element is trivially unique). For each k from 1: if nums[k] != nums[l], do l += 1; nums[l] = nums[k]. Duplicates are simply skipped. At the end the first l + 1 slots hold the distinct values in order, and l + 1 is the answer. One pass, O(n) time, O(1) space.
Solution & live demo
Edge cases
Every nums[k] differs, so l advances each step and the whole array is kept.
No nums[k] differs from nums[l]; l stays 0 and length 1 is returned.
The loop never runs; l + 1 = 1 is correct.