Remove Duplicates From an Unsorted Linked List - Problem

Given the head of a linked list, find all the values that appear more than once in the list and delete the nodes that have any of those values.

Return the linked list after the deletions.

Note: A value that appears multiple times should have all its occurrences removed from the list.

Input & Output

Example 1 — Basic Case
$ Input: head = [1,2,3,2]
Output: [1,3]
💡 Note: Value 2 appears twice, so remove all nodes with value 2. Keep nodes with values 1 and 3 that appear only once.
Example 2 — Multiple Duplicates
$ Input: head = [2,1,1,2]
Output: []
💡 Note: Both values 1 and 2 appear twice, so all nodes are removed. The result is an empty list.
Example 3 — No Duplicates
$ Input: head = [1,2,3]
Output: [1,2,3]
💡 Note: All values appear exactly once, so no nodes are removed. The original list is returned.

Constraints

  • The number of nodes in the given list is in the range [1, 105]
  • 1 ≤ Node.val ≤ 105

Visualization

Tap to expand
Remove Duplicates From Unsorted Linked ListInput List1232KeepRemoveKeepRemoveValue 2 appears twice → Remove ALL nodes with value 2Result List13Output: [1, 3]
Understanding the Visualization
1
Input
Linked list with some duplicate values
2
Process
Identify values that appear more than once
3
Output
Remove ALL nodes with duplicate values
Key Takeaway
🎯 Key Insight: Use frequency counting to identify duplicates, then remove ALL occurrences of duplicate values
Asked in
Microsoft 25 Amazon 20 Google 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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