Remove Duplicates from Sorted List II - Problem

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

For example, given 1→2→3→3→4→4→5, return 1→2→5.

Unlike the original "Remove Duplicates" problem which keeps one copy of each duplicate, this problem removes all occurrences of duplicated values completely.

Input & Output

Example 1 — Basic Case with Duplicates
$ Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
💡 Note: Values 3 and 4 appear twice, so remove all occurrences. Keep only unique values 1, 2, and 5.
Example 2 — Head Node is Duplicate
$ Input: head = [1,1,2,3]
Output: [2,3]
💡 Note: The head node value 1 is duplicated, so both 1's are removed. Only 2 and 3 remain.
Example 3 — All Elements are Duplicates
$ Input: head = [1,1,2,2]
Output: []
💡 Note: Every value appears exactly twice, so all nodes are removed, resulting in 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

Visualization

Tap to expand
Remove Duplicates from Sorted List IIInput: [1, 2, 3, 3, 4, 4, 5]1233445duplicateduplicateduplicateduplicateRemove ALL duplicate values completelyOutput: [1, 2, 5]125
Understanding the Visualization
1
Input
Sorted linked list [1,2,3,3,4,4,5] with some duplicate values
2
Process
Identify and remove ALL nodes that have duplicate values (3,3 and 4,4)
3
Output
Resulting list [1,2,5] contains only unique values
Key Takeaway
🎯 Key Insight: Use a dummy node to handle edge cases and skip entire duplicate sequences in one pass
Asked in
Microsoft 45 Amazon 38 Google 32 Facebook 28
187.5K Views
Medium-High Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen