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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code