Remove Duplicates from Sorted List II
Medium
Topics
Given the head of a sorted linked list, delete all nodes that have duplicate values, leaving only values that appear exactly once. Return the sorted list.
Example 1
Input: head = [1,2,3,3,4,4,5] Output: [1,2,5]
Example 2
Input: head = [1,1,1,2,3] Output: [2,3]
Constraints
- 0 <= number of nodes <= 300
- -100 <= Node.val <= 100
- The list is sorted in non-decreasing order.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Sortedness means every group of equal values is one contiguous run, so "appears more than once" is a local property you can decide by looking at neighbours. The job is to skip whole runs, not individual nodes.
The awkward part is that the node before a deleted run has to be relinked, and that node may be the head. A dummy node in front removes the special case entirely. Keep prev pointing at the last node known to be kept, advance cur to the end of its run, and then decide: if cur never moved the run had length one, so keep it; otherwise splice the whole run out.
Approach
- Create a dummy whose
nextis the head, withprevat the dummy andcurat the head. - Advance
curwhilecur.nextholds the same value, landing on the last node of the run. - If
prev.next == curthe run was a single node, so moveprevforward. - Otherwise set
prev.next = cur.next, dropping the run. - Advance
curand repeat.
Dry Run
input 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5
run [1] prev.next == cur, length 1 keep, prev moves to 1
run [2] prev.next == cur, length 1 keep, prev moves to 2
run [3,3] prev.next != cur splice out, prev stays at 2
run [4,4] prev.next != cur splice out, prev stays at 2
run [5] prev.next == cur, length 1 keep
answer 1 -> 2 -> 5
edge cases, verified
[1,1,1,2,3] -> 2 -> 3 the head itself is deleted
[1,1] -> empty list
[] -> empty listComplexity
- Time — O(n): each node is passed once; the inner run-walk advances the same
curthat the outer loop uses, so it is not nested work. - Space — O(1): one dummy and two pointers.
Common Pitfalls
- Working without a dummy node. Every run that includes the head then needs its own branch, which is where this problem is usually failed.
- Deleting only the extra copies and keeping one, which is remove duplicates I. Here a value that appears twice disappears completely.
- Comparing
cur.valwithprev.valto detect a run.prevpoints into the kept list, which may be far away; the run is detected by looking forward atcur.next. - Advancing
prevunconditionally. It must stay put whenever a run was removed, because the node it points at is still the last kept node. - Assuming the algorithm works on unsorted input. It relies on equal values being adjacent; given
[1,2,2,1]it removes the adjacent pair and returns1 -> 1, which is correct for the run-based rule but not what "appears exactly once" would mean globally.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head):
dummy = ListNode(0, head)
prev = dummy
cur = head
while cur:
while cur.next and cur.val == cur.next.val:
cur = cur.next
if prev.next == cur:
prev = prev.next
else:
prev.next = cur.next
cur = cur.next
return dummy.nextimport java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy, cur = head;
while (cur != null) {
while (cur.next != null && cur.val == cur.next.val) cur = cur.next;
if (prev.next == cur) prev = prev.next;
else prev.next = cur.next;
cur = cur.next;
}
return dummy.next;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
public: ListNode* deleteDuplicates(ListNode* head) {
ListNode dummy(0);
dummy.next = head;
ListNode* prev = &dummy;
ListNode* cur = head;
while (cur) {
while (cur->next && cur->val == cur->next->val) cur = cur->next;
if (prev->next == cur) prev = prev->next;
else prev->next = cur->next;
cur = cur->next;
}
return dummy.next;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode} head
* @return {ListNode}
*/ var deleteDuplicates = function(head) {
const dummy = new ListNode(0, head);
let prev = dummy, cur = head;
while (cur) {
while (cur.next && cur.val === cur.next.val) cur = cur.next;
if (prev.next === cur) prev = prev.next;
else prev.next = cur.next;
cur = cur.next;
}
return dummy.next;
};