Remove Duplicates From an Unsorted Linked List - Problem

You're given the head of a linked list that contains duplicate values scattered throughout. Your task is to completely remove all nodes that have values appearing more than once in the list.

๐ŸŽฏ Goal: If a value appears multiple times anywhere in the linked list, remove all nodes with that value - not just the duplicates!

Example: In the linked list 1 โ†’ 2 โ†’ 3 โ†’ 2 โ†’ 4, the value 2 appears twice, so we must remove both nodes containing 2, leaving us with 1 โ†’ 3 โ†’ 4.

This problem is trickier than standard duplicate removal because:

  • The linked list is unsorted, so duplicates can be anywhere
  • We must remove all instances of duplicate values, not just extras
  • We need to preserve the original order of remaining elements

Input & Output

example_1.py โ€” Basic Case
$ Input: head = [1,2,3,2]
โ€บ Output: [1,3]
๐Ÿ’ก Note: The value 2 appears twice (at positions 1 and 3), so we remove both nodes containing 2. The remaining nodes are 1 and 3, preserving their original order.
example_2.py โ€” Multiple Duplicates
$ Input: head = [2,1,1,2]
โ€บ Output: []
๐Ÿ’ก Note: Both values 1 and 2 appear twice in the list. Since every value is duplicated, we must remove all nodes, resulting in an empty list.
example_3.py โ€” No Duplicates
$ Input: head = [1,2,3,4]
โ€บ Output: [1,2,3,4]
๐Ÿ’ก Note: Each value appears exactly once, so no nodes need to be removed. The entire original list is returned unchanged.

Constraints

  • The number of nodes in the given list is in the range [1, 105]
  • Each node's value is in the range [1, 105]
  • Follow-up: Can you solve this problem in one pass?

Visualization

Tap to expand
Quality Control Assembly LineM1โœ“ UniqueM2โœ— DuplicateM3โœ“ UniqueM2โœ— RemoveM4โœ“ Unique๐Ÿ‘ทInspectorInventory LogM1: โœ“ Count = 1M2: โœ— Count = 2M3: โœ“ Count = 1M4: โœ“ Count = 1Final Result: M1 โ†’ M3 โ†’ M4M1M3M4
Understanding the Visualization
1
Inventory Pass
Walk the entire assembly line with a clipboard, recording how many times each model number appears
2
Quality Check
Mark any model numbers that appear more than once as 'defective batch'
3
Removal Pass
Walk the line again, removing ALL products whose model numbers were marked as defective
4
Final Result
Only products with unique model numbers remain on the assembly line
Key Takeaway
๐ŸŽฏ Key Insight: We need to identify ALL occurrences of duplicate values and remove them entirely, not just the extras. The two-pass approach efficiently handles this by first counting frequencies, then filtering based on those counts.
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
23.4K Views
Medium Frequency
~15 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