Remove Duplicates from Sorted Array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place so that each unique element appears only once. Return the count of unique elements k. The first k elements of nums should hold the unique values in their original order. What you leave beyond index k doesn't matter.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Edge cases: Array with one element. All elements are the same.
Sample Input
nums = [1,1,2]
Sample Output
2
Constraints
- 1 <= nums.length <= 3 * 10^4
- -100 <= nums[i] <= 100
- nums is sorted in non-decreasing order
Test Cases
Case 1
Args: [[1,1,2]]
Expected: 2
Topics
Approach: Two Pointers
Since the array is sorted, duplicates are always adjacent. Keep a slow pointer k that marks where the next unique value should go. Walk a fast pointer through the array — whenever you see a value different from nums[k-1], write it at position k and advance k.
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let k = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[k - 1]) {
nums[k] = nums[i];
k++;
}
}
return k;
}
Time Complexity: O(n)
Space Complexity: O(1)
Saved in this browser only. Private to you.