LeetCode #82 Medium

Remove Duplicates from Sorted List II

Remove Duplicates from Sorted List II is LeetCode 82 (Medium). Given the head of a sorted linked list, delete all nodes whose value occurs more than once, so only the values that appeared exactly once are left. Return the new head, still sorted.

  • A repeated value keeps no copy at all. Keeping one copy is the easier first version.
  • The head itself may be deleted, and the answer may be an empty list.
Constraints
  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.
linked listtwo pointers
Open on LeetCode ↗
02

Intuition

In a sorted list each value forms one block of neighbours. A block survives only if it has length one. You cannot tell that from the first node alone, so you look ahead: if the next node holds the same value, the whole block must go.

  • Look ahead, then decide: walk to the last node of the block, then link the node before the block straight to whatever comes after it.
  • Dummy node: the node before the first block does not exist yet, so a placeholder sits in front of the head. Deleting the first block is then the same operation as deleting any other block.
How to spot this pattern

When a value's fate depends on how many times it appears, and the list is sorted, scan block by block and keep a pointer to the last node you are sure about.

03

Approach

Try it first

Before reading on, decide which node's next you change when a block of equal values is thrown away, and what that node is when the very first block goes. Try it on [1, 1, 2]. Aim for O(n) time and O(1) extra space.

1

Put a placeholder before the head

Create dummy with dummy.next = head and set prev = dummy. prev always marks the last node that is certain to stay, and the placeholder plays that part until a real node earns it.

2

Check whether the current value repeats

With head on the first node of a block, compare it with head.next. Only a match tells you this block is longer than one node, and the list being sorted means no copy can show up later.

3

Skip the whole block

If it repeats, move head along while the next value is still equal, so head ends on the block's last node. Then set prev.next = head.next. prev stays where it is, because the node after the block has not been checked yet.

4

Keep a single node

If it does not repeat, the node is safe, so move prev onto it. Either way, step head forward to the first node of the next block. At the end return dummy.next, which may be null.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
▶3 dummy = ListNode(0, head)
▶4 prev = dummy
▶5 while head:
▶6 if head.next and head.val == head.next.val:
▶7 while head.next and head.val == head.next.val:
▶8 head = head.next
▶9 prev.next = head.next
▶10 else:
▶11 prev = prev.next
▶12 head = head.next
▶13 return dummy.next
list1233445headanswerstartprevprev starts on the placeholder
prevstart
No real node is known to stay yet, so prev sits on a placeholder in front of the list. If the first block has to go, the placeholder's link is the one that changes.
list1233445headanswerstart1prevnext is 2 → 1 is alone, keep it
prev1
The next value is bigger, so 1 appears exactly once. It is safe for good, and prev moves onto it.
list1233445headanswerstart12prevnext is 3 → 2 is alone, keep it
prev2
The next value is bigger, so 2 appears exactly once. It is safe for good, and prev moves onto it.
list1233445headanswerstart12prevnext is 3 too → this block repeats
head3
next3
Looking one node ahead shows a second 3. Because the list is sorted, every copy of 3 sits in this one block, so all of it must go.
list1233445headanswerstart12prevnext is 4 → the block ends here
head3
next4
head now stands on the last 3. The node after it is the first one the block can be linked past.
list1233445headanswerstart12prev2 now links to 4; every 3 is gone
prev.next4
prev's link jumps over the whole block in one change. prev itself does not move: 4 has not been checked yet and might start another repeated block.
list1233445headanswerstart12prevnext is 4 too → this block repeats
head4
next4
Looking one node ahead shows a second 4. Because the list is sorted, every copy of 4 sits in this one block, so all of it must go.
list1233445headanswerstart12prevnext is 5 → the block ends here
head4
next5
head now stands on the last 4. The node after it is the first one the block can be linked past.
list1233445headanswerstart12prev2 now links to 5; every 4 is gone
prev.next5
prev's link jumps over the whole block in one change. prev itself does not move: 5 has not been checked yet and might start another repeated block.
list1233445headanswerstart125prevno next node → 5 is alone, keep it
prev5
Nothing follows, so 5 appears exactly once. It is safe for good, and prev moves onto it.
list1233445answerstart125return the node after start: 1 → 2 → 5
return1
The answer begins after the placeholder, so the placeholder never shows up in the result. Only values that appeared once are left.
05

Common pitfalls

Moving prev after cutting a block

✗ Wrong
prev.next = head.next
prev = prev.next
✓ Right
prev.next = head.next

On [1, 2, 2, 3, 3], after the 2s are cut prev would jump onto the first 3 before anyone knows 3 repeats. The next cut then starts from that 3 itself, so one 3 survives and the output is [1, 3] instead of [1].

Comparing with the previous value

✗ Wrong
if head.val == last_val:  # skip head
✓ Right
if head.next and head.val == head.next.val:

Looking back only catches the second and later copies. On [1, 1, 2] the first 1 is kept because nothing equal came before it, giving [1, 2] instead of [2].

06

Edge cases

The first block repeats, as in [1, 1, 2]

prev is still the placeholder, so the cut makes dummy.next point at 2 and the returned head changes without a special case.

Every value repeats, as in [1, 1, 2, 2]

Each block is cut from the placeholder, dummy.next ends as null, and the answer is an empty list.

07

Complexity

Time
O(n)
Space
O(1)
head visits each node once, whether the outer loop or the inner block loop moves it. The placeholder and two pointers are the only extra memory.
08

Remove Duplicates from Sorted List II FAQ

Can I solve it with a hash map of counts?

Yes: count every value in one pass, then rebuild the chain keeping only values with count 1. It works even on an unsorted list, but it spends O(n) memory that the sorted order makes unnecessary.

Is there a recursive version?

Yes. If the head starts a block, skip the block and recurse on what follows it; otherwise set head.next to the recursive result and return head. It reads cleanly but uses O(n) call stack for a list with no repeats.