Remove Duplicates from Sorted Array II (LeetCode 80): Solution and Explanation
A sorted integer array must be trimmed in place so that each distinct value appears at most twice, in the original order. The kept values go in the first k slots, and the function returns k.
Intuition
A direct idea is to count the run length of each value and copy at most two of it forward. That works, but it needs a counter that resets on every new value, and it is easy to get the reset wrong.
There is a shorter test. Think of the kept prefix nums[0..k) as the answer being built. It is sorted, so if the incoming value already appears twice in it, those two copies must be the last two slots, nums[k - 2] and nums[k - 1]. Because the prefix is sorted, it is enough to look at nums[k - 2]: if it equals the incoming value, then everything from k - 2 to the end of the prefix equals it too.
So a single comparison decides each element. Keep nums[i] when k < 2 (there are not two values to compare against yet) or when nums[i] != nums[k - 2]. Keeping means copying it into nums[k] and moving k forward. The write pointer never passes the read pointer, so the copy never destroys a value that has not been read yet.
The same pattern generalizes: to allow at most m copies, compare with nums[k - m]. The problem with m = 1 is the classic Remove Duplicates from Sorted Array.
Approach: Read and write pointers, look two back
- Set
k = 0, the length of the kept prefix. - Loop
iover every index ofnums. - If
k < 2ornums[i] != nums[k - 2], copynums[i]intonums[k]and incrementk. - Otherwise skip the element; it would be a third copy.
- Return
k.
Step-by-step example
nums = [1,1,1,2,2,3]
i = 0andi = 1:kis below 2, so both 1s are kept andkbecomes 2.i = 2: the value 1 equalsnums[k - 2] = nums[0] = 1, so it is a third copy and is skipped.kstays 2.i = 3: the value 2 differs fromnums[0] = 1, so it is copied intonums[2]andkbecomes 3. The array is now [1,1,2,2,2,3].i = 4: the value 2 differs fromnums[1] = 1, so it is copied intonums[3]andkbecomes 4.i = 5: the value 3 differs fromnums[2] = 2, so it is copied intonums[4]andkbecomes 5.- The prefix [1,1,2,2,3] is the answer and the function returns 5.
Code: Python, Java, C++
1class Solution:
2 def removeDuplicates(self, nums: List[int]) -> int:
3 k = 0
4 for i in range(len(nums)):
5 if k < 2 or nums[i] != nums[k - 2]:
6 nums[k] = nums[i]
7 k += 1
8 return k1class Solution {
2 public int removeDuplicates(int[] nums) {
3 int k = 0;
4 for (int i = 0; i < nums.length; i++) {
5 if (k < 2 || nums[i] != nums[k - 2]) {
6 nums[k] = nums[i];
7 k++;
8 }
9 }
10 return k;
11 }
12}1class Solution {
2public:
3 int removeDuplicates(vector<int>& nums) {
4 int k = 0;
5 for (int i = 0; i < (int)nums.size(); i++) {
6 if (k < 2 || nums[i] != nums[k - 2]) {
7 nums[k] = nums[i];
8 k++;
9 }
10 }
11 return k;
12 }
13};Time and space complexity
O(n)
Each element is read once and written at most once.
O(1)
Only the two indices are stored; the array is rewritten in place.
Other approaches
Run-length counter (time O(n), space O(1))
Track how many times the current value has been seen in a row and copy it forward only while the count is at most 2. Same complexity, but it needs extra state that must be reset whenever the value changes.
Build a new list (time O(n), space O(n))
Append each value to a new list unless the list already ends with two copies of it, then copy the list back. Simple to reason about, but it uses O(n) extra memory, which the problem forbids.
Common mistakes
- Comparing with
nums[i - 2]instead ofnums[k - 2]. The original neighbors may already have been overwritten or skipped, so only the kept prefix tells you how many copies are kept. - Comparing with
nums[k - 1]only. That allows one copy, which solves the easier problem and drops the allowed second copy. - Forgetting the
k < 2guard, which readsnums[-2](the end of the list in Python) or crashes in other languages. - Deleting elements with
poporeraseinside the loop, which shifts the array and makes the whole thing O(n²).
Frequently asked questions
Why is comparing with nums[k - 2] enough?
The kept prefix is sorted. If nums[k - 2] equals the incoming value, then nums[k - 1] sits between it and the incoming value in sorted order, so it is equal as well. That means two copies are already kept.
Can the write overwrite a value that has not been read yet?
No. k only grows when an element is kept, and each kept element was read first, so k <= i at every write. The slot being written was already read.
How do I allow at most three copies instead of two?
Replace 2 with 3 in both places: keep nums[i] when k < 3 or nums[i] != nums[k - 3]. The same argument about the sorted prefix holds for any limit.
What does the judge check here?
It checks the kept values. After your function returns, the judge prints nums[0:k] using the k you returned and compares it with the expected prefix, the same way LeetCode inspects the first k slots. A correct count with wrong values fails.