InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Remove Duplicates from Sorted List II

medium Original ↗ 00:00

Problem

You are given the head of a sorted singly linked list. Delete every node whose value appears more than once, removing all occurrences of any duplicated value rather than only the extra copies. Return the head of the resulting list, which must remain sorted.

This differs from “Remove Duplicates I”, where you keep one copy of each value. Here any value that appears more than once is removed 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 are removed, including the head.
  • Input: head = [1, 1] → Output: [] Both values are duplicates, so 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug