Approach Summary
Slow pointer is the write head. Fast pointer scans; write only when a new unique element is found.
Full Solution & Approach
The array is sorted, so every duplicate of a value sits directly next to the original. Use a write pointer that tracks where the next unique element should be placed and a read pointer that scans the array. For every element, if it differs from the previous element written, copy it to the write position and advance the write pointer; otherwise skip it. Since the input is sorted, "different from the previous written element" is exactly the condition for being a new unique value. At the end the first k positions hold the unique elements in order and k is the answer. This is the in-place filter pattern: a read pointer always advances, a write pointer only advances when something should be kept. The same skeleton removes zeroes, removes elements by value, and compresses in place.
A single pass where each element is read once and written at most once — O(n) time. No extra arrays — O(1) space.
Solution Code
Solution
def remove_duplicates(nums: list[int]) -> int:
write = 0
for read in range(len(nums)):
if write == 0 or nums[read] != nums[write - 1]:
nums[write] = nums[read]
write += 1
return writefunction removeDuplicates(nums) {
let write = 0;
for (let read = 0; read < nums.length; read++) {
if (write === 0 || nums[read] !== nums[write - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}public int removeDuplicates(int[] nums) {
int write = 0;
for (int read = 0; read < nums.length; read++) {
if (write == 0 || nums[read] != nums[write - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}int removeDuplicates(vector<int>& nums) {
int write = 0;
for (int read = 0; read < (int)nums.size(); read++) {
if (write == 0 || nums[read] != nums[write - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
} Edge Cases to Watch
- Empty array — return 0
- All elements identical — k is 1
- No duplicates — k equals the array length and no writes shift anything
- Single element — return 1
How to Recognize This Pattern
- In-place deduplication of sorted array
Complexity Analysis
Time Complexity
O(n)
Space Complexity
O(1)