Remove Duplicates from Sorted Array Algorithm
You have a sorted array of integers. Remove duplicates in-place so each value appears only once. Return the count of unique elements.
27 Mar 2024

You have a sorted array of integers. Remove duplicates in-place so each value appears only once. Return the count of unique elements.
The catch: you can't allocate a new array. Modify the original. Only the first k elements matter — whatever's left beyond that is irrelevant.
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
The intuition
Since the array is already sorted, duplicates sit next to each other. Use two pointers: one slow (writeIndex) to mark where the next unique element goes, and one fast (i) to scan ahead.
When nums[i] differs from nums[writeIndex], we found a new unique value. Copy it forward and advance the write pointer.
var removeDuplicates = function(nums) {
if (nums.length === 0) return 0;
let writeIndex = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[writeIndex - 1]) {
nums[writeIndex] = nums[i];
writeIndex++;
}
}
return writeIndex;
};
Complexity
- Time: O(n) — one pass.
- Space: O(1) — in-place.
The trade-off
This only works because the input is sorted. Unsorted arrays need a different strategy (usually a Set, which costs O(n) space). Always check your preconditions before picking an approach.