Given a sorted array, remove duplicates in place so each element appears once, returning the new length (e.g. [1,1,2,3,3] -> [1,2,3], length 3).
Because the array is sorted, duplicates are adjacent. Use a slow pointer marking the last unique position and a fast pointer scanning ahead; when the fast element differs from the last unique, copy it forward. O(n) time, O(1) space.
public static int removeDuplicates(int[] a) {
if (a.length == 0) return 0;
int slow = 0;
for (int fast = 1; fast < a.length; fast++) {
if (a[fast] != a[slow]) a[++slow] = a[fast];
}
return slow + 1;
}function removeDuplicates(a) {
if (a.length === 0) return 0;
let slow = 0;
for (let fast = 1; fast < a.length; fast++) {
if (a[fast] !== a[slow]) a[++slow] = a[fast];
}
return slow + 1;
}def remove_duplicates(a):
if not a:
return 0
slow = 0
for fast in range(1, len(a)):
if a[fast] != a[slow]:
slow += 1
a[slow] = a[fast]
return slow + 1In-place two-pointer compaction is a fundamental array technique reused for filtering and partitioning without extra allocation.
Why does the in-place approach rely on the array being sorted?