Remove Duplicates from Sorted Array(#26)
Category: Array, Two Pointer
π§© Problem Statement
Youβre given a sorted array of integers. You need to remove duplicates in-place so that each element appears only once. Return the number of unique elements `k`, and modify the input array such that the first `k` elements are the unique ones. Their order should be preserved. Values beyond index `k-1` can be ignored.
π Examples
Input: nums = [1, 1, 2]
Output: 2
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5
π§ Approach
### Two Pointer Approach
We use two pointers `first` and `sec`.
- `first` tracks the position of the last unique element.
- `sec` scans the array for the next unique element.
If we find a new unique number at `sec`, we move `first` forward and swap it with `sec`. At the end, `first + 1` gives the total count of unique elements.
π» Code
var removeDuplicates = function (nums) {
let first = 0;
let sec = 1;
while (sec < nums.length) {
if (nums[first] === nums[sec]) {
sec++;
} else {
first++;
[nums[first], nums[sec]] = [nums[sec], nums[first]];
sec++;
}
}
console.log(nums.slice(0, first + 1)); // Shows the unique values
return first + 1;
};
console.log(removeDuplicates([0,0,1,1,1,2,2,3,3,4])); // Output: 5
π Complexity
Time: O(n) β one pass through the array.
Space: O(1) β in-place solution using no extra space.