Skip to content
thesarfo

Reference

Remove Duplicates In-Place from a Sorted Array

Deduplicating a sorted array in place using a HashSet vs. the two-pointer technique that exploits the existing order.

views 0

[1,1,2,2,2,3,3] → return 3 (unique elements), with the array’s front holding [1,2,3,...].

Brute force: dump everything into a HashSet (which drops duplicates automatically), then write the set’s contents back into the array.

Optimal — two pointers (since the array is already sorted, you don’t need a set): i marks where the next unique value goes, j scans forward looking for the next value that differs from arr[i].

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int i = 0;
for(int j = 1; j < nums.size(); j++){
if(nums[j] != nums[i]){
nums[i + 1] = nums[j];
i++;
}
}
return i + 1;
}
};

For [1,1,2,2,2,3,3]: j=1 no change (nums[1]==nums[0]); j=2, nums[2]!=nums[0] so nums[1]=2, i=1; continuing, the array becomes [1,2,3,_,_,_,_] and the function returns 3.