LeetCode #80 Medium

Remove Duplicates from Sorted Array II

Remove Duplicates from Sorted Array II is LeetCode 80 (Medium). The integer array nums is sorted in non-decreasing order. Rewrite it in place so that every value appears at most twice, keep the order, and return k, the length of what is left.

  • Only nums[0..k-1] is checked; later slots can hold anything.
  • Extra memory must stay O(1), so no copy of the array.
Constraints
  • 1 <= nums.length <= 3 * 10⁴
  • -10⁴ <= nums[i] <= 10⁴
  • nums is sorted in non-decreasing order.
two-pointersarrays
Open on LeetCode ↗
02

Intuition

Call the front of the array, nums[0..k-1], the kept part. It is sorted, and no value appears in it more than twice.

A value x may join the kept part unless it equals nums[k - 2], the element two slots back. If x == nums[k - 2], then sorting forces nums[k - 1] to be x too, because it sits between them. Two copies are already kept and x would be the third. If x differs, at most one copy is kept so far, so a second is allowed.

One comparison replaces a run counter, and the first two values always pass because there is nothing two slots back yet.

03

Approach

1

Start with an empty kept part

Set k = 0. The kept part is nums[0..k-1], and it grows only from the left, so it never overtakes the element being read.

2

Let the first two values in

While k < 2, keep every value. Any value is allowed twice, so the first two reads can never break the rule.

3

Compare with the slot two back

For every later value x, compare it with nums[k - 2]. Equal means two copies of x are already kept, so skip it. Different means write x to nums[k] and add 1 to k.

4

Return k

Once every value is read, the kept part holds each value once or twice, in sorted order, and k is its length.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def removeDuplicates(self, nums: List[int]) -> int:
▶3 k = 0
▶4 for x in nums:
▶5 if k < 2 or x != nums[k - 2]:
▶6 nums[k] = x
▶7 k += 1
▶8 return k
nums111223kept part is empty, k = 0checknext1vsnothing two back yetstart: nothing is kept yet
k0
The kept part is the front of the array, nums[0..k-1]. It starts empty and only grows from the left, so it never runs past the value being read.
nums111223kept part is empty, k = 0checknext1vsnothing two back yetfewer than 2 kept → 1 is always allowed
next1
two backnone
k0
With fewer than two values kept, no value can already appear twice, so 1 passes without a comparison.
nums111223kept part, k = 1checknext1vsnothing two back yet1 written to slot 0 → kept part has 1
nums[0]1
k1
No value has been skipped yet, so slot 0 is the value's own place and it is written onto itself.
nums111223kept part, k = 1checknext1vsnothing two back yetfewer than 2 kept → 1 is always allowed
next1
two backnone
k1
With fewer than two values kept, no value can already appear twice, so 1 passes without a comparison.
nums111223kept part, k = 2checknext1vsnothing two back yet1 written to slot 1 → kept part has 2
nums[1]1
k2
No value has been skipped yet, so slot 1 is the value's own place and it is written onto itself.
nums111223kept part, k = 2checknext1=1two slots back, slot 01 equals 1 two back → third copy, skip
next1
two back1
k2
Slot 0 already holds 1. The kept part is sorted, so slot 1 between them is 1 too. Two copies are kept; this one would be the third.
nums111223kept part, k = 2checknext2≠1two slots back, slot 02 differs from 1 two back → keep
next2
two back1
k2
Slot 0 holds 1, not 2. So at most one 2 is kept so far (in slot 1 at most), and a second copy is allowed.
nums112223kept part, k = 3checknext2≠1two slots back, slot 02 written to slot 2 → kept part has 3
nums[2]2
k3
Slot 2 held a skipped copy that was already read, so it can be overwritten. The bracket grows by one.
nums112223kept part, k = 3checknext2≠1two slots back, slot 12 differs from 1 two back → keep
next2
two back1
k3
Slot 1 holds 1, not 2. So at most one 2 is kept so far (in slot 2 at most), and a second copy is allowed.
nums112223kept part, k = 4checknext2≠1two slots back, slot 12 written to slot 3 → kept part has 4
nums[3]2
k4
Slot 3 held a skipped copy that was already read, so it can be overwritten. The bracket grows by one.
nums112223kept part, k = 4checknext3≠2two slots back, slot 23 differs from 2 two back → keep
next3
two back2
k4
Slot 2 holds 2, not 3. So at most one 3 is kept so far (in slot 3 at most), and a second copy is allowed.
nums112233kept part, k = 5checknext3≠2two slots back, slot 23 written to slot 4 → kept part has 5
nums[4]3
k5
Slot 4 held a skipped copy that was already read, so it can be overwritten. The bracket grows by one.
nums112233kept part, k = 5return5length of the kept partreturn 5: no value appears more than twice
k5
kept1, 1, 2, 2, 3
All 6 values are read. The answer is 5; the faded slots after the bracket are leftovers the judge ignores.
05

Common pitfalls

Looking two back in the input instead of the kept part

✗ Wrong
if i < 2 or nums[i] != nums[i - 2]:
    nums[k] = nums[i]
    k += 1
✓ Right
if k < 2 or nums[i] != nums[k - 2]:
    nums[k] = nums[i]
    k += 1

Writes go into the same array, so nums[i - 2] may already hold a copied value. On [1, 1, 1, 2, 2] the 2 copied into slot 2 makes the last 2 look like a third copy, and the answer is 3 instead of 4.

Checking only the previous slot

✗ Wrong
if k < 1 or x != nums[k - 1]:
✓ Right
if k < 2 or x != nums[k - 2]:

Looking one slot back keeps each value once, which is the stricter rule of the first version. [1, 1, 2] returns 2, but the right answer is 3.

06

Edge cases

Fewer than three elements, e.g. [7, 7]

Both values pass the k < 2 test, so the array is returned whole without ever reading a negative index.

A long run, e.g. [4, 4, 4, 4, 4]

The first two 4s are kept. Every later 4 equals nums[0], which is two back from k = 2, so k stays at 2.

07

Complexity

Time
O(n)
Space
O(1)
One pass with one comparison per element; the kept part lives inside nums itself.
08

Remove Duplicates from Sorted Array II FAQ

How do I allow each value up to m times instead of 2?

Replace both 2s with m: keep x when k < m or x != nums[k - m]. The same sorting argument holds, since a match m slots back means the last m kept values are all x. With m = 1 you get Remove Duplicates from Sorted Array.

Can I count the length of each run instead?

Yes. Track the current value and how many times it has been kept, and reset the count when the value changes. It gives the same result with two extra variables and one more branch.