Remove Duplicates from Sorted List II (LeetCode 82): Solution and Explanation

Medium
Linked List
Two Pointers

You get the head of a sorted singly linked list. Delete every node whose value appears more than once, keeping only values that were unique to begin with, and return the head of what is left.

Intuition

Sorting puts every copy of a value in one consecutive run. So the question for each value is simply whether its run has length one. If it does, the node stays; if not, the whole run goes, including the first copy.

Because the first copy goes too, the head of the list can disappear. That is the classic sign you want a dummy node: a fake node placed before the head, so every real node has a predecessor whose next you can rewire.

Two pointers do the work. prev sits on the last node that is known to survive (initially the dummy). curr explores ahead. When curr and curr.next hold the same value, curr slides to the end of that run and prev.next jumps straight past it.

prev only moves when curr turns out to be unique. After a cut, the node right after the run has not been checked, and it might start another duplicated run, so prev has to wait.

Approach: Dummy node with prev and curr pointers

  1. Create dummy with dummy.next = head. Set prev = dummy and curr = head.
  2. While curr is not null, check whether curr.next exists and has the same value as curr.
  3. If it does, move curr forward while the next value still matches, so curr ends on the last copy. Then set prev.next = curr.next to unlink the whole run.
  4. If it does not, curr is unique, so move prev = prev.next (which is curr).
  5. In both cases move curr = curr.next. When the loop ends, return dummy.next.

Step-by-step example

head = [1,2,3,3,4,4,5]
  1. dummy points at 1. prev is on dummy, curr on 1.
  2. 1 differs from 2, so it is unique: prev moves to 1, curr to 2. The same happens for 2.
  3. curr is on 3 and the next node is also 3. curr slides to the second 3, then prev.next = curr.next links 2 straight to the first 4.
  4. curr moves to 4, which also has a twin. curr slides to the second 4, and 2 is linked to 5. prev is still on 2.
  5. 5 has no next node, so it is unique and prev steps onto it. curr becomes null and the loop ends.
  6. dummy.next is 1, and the list reads [1,2,5].

Code: Python, Java, C++

1class Solution:
2    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
3        dummy = ListNode(0, head)
4        prev = dummy
5        curr = head
6        while curr:
7            if curr.next and curr.next.val == curr.val:
8                while curr.next and curr.next.val == curr.val:
9                    curr = curr.next
10                prev.next = curr.next
11            else:
12                prev = prev.next
13            curr = curr.next
14        return dummy.next
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

curr moves forward on every inner and outer step and never moves back, so each node is visited once.

Space

O(1)

Only the dummy node and two pointers are added, whatever the list length.

Other approaches

Count values, then rebuild (time O(n), space O(n))

Count how often each value appears in one pass, then link together only the nodes whose count is 1. Easy to reason about, but it needs a hash map and two passes, and it ignores the sorted order.

Recursion (time O(n), space O(n))

If the head starts a duplicated run, skip the whole run and recurse on what follows; otherwise set head.next to the recursive result and return head. Compact, but the call stack grows with the list.

Common mistakes

  • Keeping one copy of a repeated value. That is the easier problem (83); here the first copy must be removed too.
  • Skipping the dummy node. Without it, a run at the very start, such as [1,1,2], needs special code to change the head.
  • Moving prev after a cut. The node after the run might begin another run, as in [1,1,2,2], so prev must stay until a node proves unique.
  • Reading curr.next.val without checking that curr.next exists, which crashes on the last node.

Frequently asked questions

How is this different from Remove Duplicates from Sorted List?

In the first version each value keeps one node. In this version any value that appears more than once loses all of its nodes, so [1,1,2] becomes [2] instead of [1,2].

Why is a dummy node needed?

The head can belong to a duplicated run and be removed. With a dummy in front, removing the head is the same prev.next = ... assignment as removing any other node, and dummy.next is always the correct answer.

Why does prev not move after deleting a run?

prev marks the last node that is definitely in the answer. The node after a deleted run has not been compared with its neighbour yet, so it is not confirmed until the next iteration.

What is the complexity?

O(n) time, since curr passes each node once, and O(1) extra space.