InterviewPrepKit

Home / Coding / Linked List

Remove Duplicates from Sorted List II

medium Original β†—
Solving tips
  • Because the list is sorted, all copies of a value form one consecutive run, so 'is duplicated' is decidable by peeking one node ahead.
  • Use a dummy node before the head (the head itself may be deleted) and a prev pointer to the last node guaranteed to survive.
  • When you detect a run, skip the entire run and set prev.next past it, but do NOT advance prev, since the next node may start another duplicate run.
  • Aim for O(n) time, O(1) space; don't confuse this with Remove Duplicates I, which keeps one copy.

Problem

You are given the head of a sorted singly linked list. Delete every node whose value appears more than once β€” not just the extra copies, but all occurrences of any duplicated value. Return the head of the resulting list, which must remain sorted.

This is the stricter sibling of β€œRemove Duplicates I”, where you keep one copy of each value; here a duplicated value is wiped out entirely.

Examples

  • Input: head = [1, 2, 3, 3, 4, 4, 5] β†’ Output: [1, 2, 5] 3 and 4 each appear twice, so every 3 and 4 is deleted.
  • Input: head = [1, 1, 1, 2, 3] β†’ Output: [2, 3] The value 1 appears three times, so all three nodes go β€” including the head.
  • Input: head = [1, 1] β†’ Output: [] Everything is a duplicate; the result is the empty list.

Constraints

  • 0 <= n <= 300 where n is the number of nodes.
  • -100 <= Node.val <= 100.
  • The list is sorted in non-decreasing order β€” this is what lets duplicates be detected locally, as consecutive runs.

Think about it first

Hint 1 Because the list is sorted, all copies of a value sit in one consecutive run. How do you tell whether a run has length 1 or more without counting the whole list first?
Hint 2 The head itself might be deleted (example 2). What standard trick gives every deletable node a predecessor?
Hint 3 Use a dummy node before the head and keep `prev` = last node known to survive. Look at `prev.next`: if its value repeats, advance a scanner past the whole run and set `prev.next` to the node after the run β€” without moving `prev`. If it doesn't repeat, `prev` advances.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.