Remove Duplicates from Sorted List II (LeetCode 82): Solution and Explanation
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
- Create
dummywithdummy.next = head. Setprev = dummyandcurr = head. - While
curris not null, check whethercurr.nextexists and has the same value ascurr. - If it does, move
currforward while the next value still matches, socurrends on the last copy. Then setprev.next = curr.nextto unlink the whole run. - If it does not,
curris unique, so moveprev = prev.next(which iscurr). - In both cases move
curr = curr.next. When the loop ends, returndummy.next.
Step-by-step example
head = [1,2,3,3,4,4,5]
- dummy points at 1.
previs on dummy,curron 1. - 1 differs from 2, so it is unique:
prevmoves to 1,currto 2. The same happens for 2. curris on 3 and the next node is also 3.currslides to the second 3, thenprev.next = curr.nextlinks 2 straight to the first 4.currmoves to 4, which also has a twin.currslides to the second 4, and 2 is linked to 5.previs still on 2.- 5 has no next node, so it is unique and
prevsteps onto it.currbecomes null and the loop ends. dummy.nextis 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.next1class Solution {
2 public ListNode deleteDuplicates(ListNode head) {
3 ListNode dummy = new ListNode(0, head);
4 ListNode prev = dummy;
5 ListNode curr = head;
6 while (curr != null) {
7 if (curr.next != null && curr.next.val == curr.val) {
8 while (curr.next != null && curr.next.val == curr.val) {
9 curr = curr.next;
10 }
11 prev.next = curr.next;
12 } else {
13 prev = prev.next;
14 }
15 curr = curr.next;
16 }
17 return dummy.next;
18 }
19}1class Solution {
2public:
3 ListNode* deleteDuplicates(ListNode* head) {
4 ListNode dummy(0, head);
5 ListNode* prev = &dummy;
6 ListNode* curr = head;
7 while (curr) {
8 if (curr->next && curr->next->val == curr->val) {
9 while (curr->next && curr->next->val == curr->val) {
10 curr = curr->next;
11 }
12 prev->next = curr->next;
13 } else {
14 prev = prev->next;
15 }
16 curr = curr->next;
17 }
18 return dummy.next;
19 }
20};Time and space complexity
O(n)
curr moves forward on every inner and outer step and never moves back, so each node is visited once.
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
prevafter a cut. The node after the run might begin another run, as in [1,1,2,2], soprevmust stay until a node proves unique. - Reading
curr.next.valwithout checking thatcurr.nextexists, 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.