82/670

82. Remove Duplicates from Sorted List II

Medium

You receive the head of a singly linked list whose values are sorted in non-decreasing order. Delete every node whose value appears more than once — when a value is duplicated, no copy of it survives — and return the head of what remains, still in sorted order.

So [1, 2, 3, 3, 4, 4, 5] collapses to [1, 2, 5]: the 3s and 4s vanish entirely rather than being trimmed down to one copy. Note the head itself can be among the deleted nodes.

Deleting whole runs: [1, 2, 3, 3, 4, 4, 5] → [1, 2, 5]
before1233445both runs are cut out — 2 links straight to 5after — no copy of a duplicated value survives125

Example 1:

Input: head = [1, 2, 3, 3, 4, 4, 5]

Output: [1, 2, 5]

Explanation: 3 and 4 each appear twice, so all four of those nodes are deleted; 1, 2, and 5 are unique and survive.

Example 2:

Input: head = [1, 1, 1, 2, 3]

Output: [2, 3]

Explanation: The three leading 1s are all removed — including the original head — leaving [2, 3].

Constraints:

  • 0 ≤ number of nodes ≤ 300
  • -100 ≤ node value ≤ 100
  • The list is sorted in non-decreasing order.

Hints:

Because the list is sorted, equal values sit next to each other — every duplicated value forms one contiguous run. You never need a full frequency table, just a look one node ahead.

The head might die. A dummy node parked in front of the head makes 'delete the first real node' the same operation as deleting any other node.

Keep `prev` pointing at the last node that is guaranteed to survive. When `cur` starts a run of length ≥ 2, advance `cur` past the entire run and splice with `prev.next = cur` — without moving `prev`, since the next run might also need deleting.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: head = [1, 2, 3, 3, 4, 4, 5]

Expected output: [1, 2, 5]