Remove duplicates from a sorted array
Easy TimeO(n) SpaceO(1)
Given a sorted array nums, remove the duplicates in place so each distinct value appears once, and return how many distinct values there are. The distinct values have to end up at the front, in order; whatever sits past the returned count is ignored, whatever it holds.
Examples
Example 1
- Input
- nums = [1, 1, 2, 2, 2, 3, 4, 4]
- Output
- The distinct values are
41, 2, 3, 4, and they now sit at the front in that order.
Example 2
- Input
- nums = [5, 5, 5]
- Output
- One distinct value, so only
1nums[0]is part of the answer.
The Code
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let write = 1;
for (let read = 1; read < nums.length; read++) {
if (nums[read] !== nums[write - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}
removeDuplicates([1, 1, 2, 2, 2, 3, 4, 4]);Done
More like this
All two pointers examples (9) →- Two sum Walk two pointers inward until the pair sums to the target.
- Reverse array Swap the ends and step inward until the pointers meet.
- Most water Widest gap first; always move the shorter wall inward.
- Valid palindrome March inward from both ends, comparing as you go.
- 3Sum Fix one number, then two-pointer the rest toward zero.
- Sort colors Three pointers sweep 0s to the front and 2s to the back in one pass.