Remove Duplicates from Sorted Array II Algorithm
The previous problem said "no duplicates at all." This one says "each element can appear at most twice." Small rule change, same core technique.
27 Mar 2024

The previous problem said "no duplicates at all." This one says "each element can appear at most twice." Small rule change, same core technique.
You get a sorted integer array. Remove extras so no value shows up more than twice. Do it in-place with O(1) extra memory. Return the new length.
Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
The intuition
Use a slow pointer to track where the next valid element goes. Walk a fast pointer through the array. The trick: compare the current element to the one two positions back in the "kept" portion. If it's the same, skip it. If it's different, keep it.
This works because the array is sorted. If nums[i] === nums[writeIndex - 2], that means we've already kept two copies of this value.
var removeDuplicates = function(nums) {
let writeIndex = 0;
for (let i = 0; i < nums.length; i++) {
if (writeIndex < 2 || nums[i] !== nums[writeIndex - 2]) {
nums[writeIndex] = nums[i];
writeIndex++;
}
}
return writeIndex;
};
Complexity
- Time: O(n) — single pass through the array.
- Space: O(1) — no extra allocation.
Why this matters
This pattern generalizes. Want at most 3 copies? Change the 2 to 3. The two-pointer approach for in-place array manipulation shows up constantly in interviews and real systems where you can't afford to allocate a new array.
The trade-off: you mutate the input. That's fine when the caller expects it. Dangerous when they don't.