Skip to content
Problem 82 · LeetCode 82(opens in a new tab)

Remove Duplicates from Sorted List II

MediumLinked lists

You get the head of a linked list whose values are sorted from small to large. Some values may show up more than once.

Remove every node whose value is repeated, including all of its copies, so that only values that appeared exactly once are left. Return the head of the remaining list, still in sorted order.

Example 1

Input:  head = [2, 4, 4, 7, 9, 9, 9, 11]
Output: [2, 7, 11]
Why:    4 and 9 repeat, so every copy goes
2 more examples and the constraints

Example 2

Input:  head = [3, 3, 6, 8]
Output: [6, 8]
Why:    the head itself is part of a run

Example 3

Input:  head = [5, 5]
Output: []
Why:    nothing appears only once

Constraints

  • 0 ≤ number of nodes ≤ 300
  • −100 ≤ each node value ≤ 100
  • The values are in non-decreasing order.

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Copy values, rebuildO(n)
  2. Skip runs in placeO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeExtra memory for 300 nodesVerdict
Copy values, rebuildO(n)
Passes; copies everything
Skip runs in placeO(n)
Best; constant memory

n = number of nodes. Both read the list once; only the copy needs O(n) extra memory.

Edge cases to test

  • Empty list. With no nodes, return an empty list.
  • Run at the head. [3, 3, 6, 8] must return [6, 8]. The dummy node handles it.
  • Run at the tail. In [2, 7, 9, 9], 7 must end up pointing to null.
  • Everything repeats. [4, 4, 4, 4] becomes an empty list.
  • No repeats. [1, 2, 3] comes back unchanged.

Common mistakes

  • Keeping one copy of each repeated value. That is the easier version of this problem; here every copy goes.
  • Moving prev forward right after cutting a run, so a second run that starts right after the first is not removed.
  • Returning head instead of dummy.next, which is wrong when the first values repeat.

How to talk through it

  1. 1Clarify. Confirm that all copies of a repeated value go, not just the extras, and that the list can be empty.
  2. 2Use the sort. Equal values sit next to each other, so a repeat is visible by looking one node ahead.
  3. 3Name the pointers. prev is the last node that stays; cur is the node being judged. Add a dummy for runs at the head.
  4. 4Code the skip. Slide cur to the end of a run, then set prev.next past it, and leave prev in place.
  5. 5Test out loud. Run [3, 3, 6, 8], [5, 5] and two runs back to back like [1, 1, 2, 2, 3].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?