Remove Duplicates from Sorted Array
Pattern: Two pointers
In a sorted array, keep one copy of each value at the front by writing a value only when it differs from the last one written.
The problem
You are given an array nums sorted in non-decreasing order. Change it in place so that its first k slots hold each
distinct value once, in order, and return k. What is left after slot k - 1 does not matter. For example, [1, 1, 2]
returns 2, with the array starting [1, 2, ...].
The function name removeDuplicates matches LeetCode. Use the link above for the exact statement.
Think first
- In a sorted array, where are all the copies of a value?
- How do you know a value is new, by comparing it with just one other value?
- Which index tells you where the next new value should go?
Hints
Brute force, and why it fails
Put everything into a set and write the sorted set back: O(n log n) time and O(n) extra memory. Deleting each duplicate by shifting the rest left is in place but O(n²).
The key insight
Sorted order makes "is this new?" a single comparison with the last kept value. A read pointer scans and a write pointer compacts, all in one pass.
Dry run
| write | 1 |
|---|
nums = [1, 1, 2, 2, 3]. The first value is always kept, so write starts at 1.
The plan
write = 1
for read from 1 to n - 1:
if nums[read] != nums[write - 1]:
nums[write] = nums[read]
write = write + 1
return write
Complexity
- Time
O(n)- Space
O(1)
One pass and two indexes.
Edge cases
- One element:
k = 1. - All equal, as in
[-3, -3, -3]:k = 1. - All distinct: every value is copied onto itself and
k = n.
I've built my logic, show the code
Java
class Solution {
public int removeDuplicates(int[] nums) {
int write = 1; // nums[0..write-1] holds the distinct values so far
for (int read = 1; read < nums.length; read++) {
if (nums[read] != nums[write - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}
}C++
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int write = 1; // nums[0..write-1] holds the distinct values so far
for (int read = 1; read < static_cast<int>(nums.size()); read++) {
if (nums[read] != nums[write - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}
};Python
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
write = 1 # nums[0..write-1] holds the distinct values so far
for read in range(1, len(nums)):
if nums[read] != nums[write - 1]:
nums[write] = nums[read]
write += 1
return writeCommon mistakes
- Using this method on an unsorted array, where copies of a value are not next to each other.
- Returning
write - 1instead ofwrite. - Starting
writeat 0, which makes the first comparison readnums[-1].