Remove Duplicates from Sorted Array
You're given nums, an integer array already sorted in non-decreasing order. Modify it in-place so every distinct value appears exactly once, then return k, the number of distinct values. After your changes, the first k positions of nums must hold those distinct values in their original relative order — whatever sits past index k doesn't matter.
Edge cases: A single-element array. An array where every element is identical.
Sample Input and Output
Example 1 · Run Sample
nums = [1,1,2] {"k":2,"nums":[1,2]} Example 2
nums = [1,1,1] {"k":1,"nums":[1]} - 1 <= nums.length <= 3 * 10^4
- -100 <= nums[i] <= 100
- nums is sorted in non-decreasing order
Test Cases (2)
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.