Remove Duplicates from Sorted Array II (LeetCode 80): Solution and Explanation

Medium
Array
Two Pointers

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

  1. Set k = 0, the length of the kept prefix.
  2. Loop i over every index of nums.
  3. If k < 2 or nums[i] != nums[k - 2], copy nums[i] into nums[k] and increment k.
  4. Otherwise skip the element; it would be a third copy.
  5. Return k.

Step-by-step example

nums = [1,1,1,2,2,3]
  1. i = 0 and i = 1: k is below 2, so both 1s are kept and k becomes 2.
  2. i = 2: the value 1 equals nums[k - 2] = nums[0] = 1, so it is a third copy and is skipped. k stays 2.
  3. i = 3: the value 2 differs from nums[0] = 1, so it is copied into nums[2] and k becomes 3. The array is now [1,1,2,2,2,3].
  4. i = 4: the value 2 differs from nums[1] = 1, so it is copied into nums[3] and k becomes 4.
  5. i = 5: the value 3 differs from nums[2] = 2, so it is copied into nums[4] and k becomes 5.
  6. 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 k
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each element is read once and written at most once.

Space

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 of nums[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 < 2 guard, which reads nums[-2] (the end of the list in Python) or crashes in other languages.
  • Deleting elements with pop or erase inside 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.