Remove Duplicates from Sorted List II - Problem
You are given the head of a sorted linked list. Your task is to remove all nodes that have duplicate numbers, leaving only the nodes that appear exactly once in the original list.
Unlike the classic "remove duplicates" problem where you keep one copy of each duplicate, here you must completely eliminate all nodes that appear more than once.
Example: If your list contains [1,2,3,3,4,4,5], the result should be [1,2,5] because 3 and 4 appeared multiple times and must be completely removed.
Return the head of the modified linked list, which should remain sorted.
Input & Output
example_1.py โ Basic case with duplicates
$
Input:
head = [1,2,3,3,4,4,5]
โบ
Output:
[1,2,5]
๐ก Note:
Numbers 3 and 4 appear more than once, so they are completely removed. Only 1, 2, and 5 appear exactly once.
example_2.py โ All duplicates
$
Input:
head = [1,1,1,2,3]
โบ
Output:
[2,3]
๐ก Note:
Number 1 appears three times, so all occurrences are removed. Numbers 2 and 3 appear exactly once.
example_3.py โ Edge case - all nodes are duplicates
$
Input:
head = [1,1,2,2,3,3]
โบ
Output:
[]
๐ก Note:
Every number 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]
- Node values are in the range [-100, 100]
- The list is guaranteed to be sorted in ascending order
Visualization
Tap to expand
Understanding the Visualization
1
Set Up Security
Place a security checkpoint (dummy head) before the guest list
2
Check Each Guest
Scan through the list looking for duplicate names
3
Remove Entire Groups
When duplicates found, remove ALL instances of that name
4
Keep Unique Guests
Only guests with unique names get to stay on the VIP list
Key Takeaway
๐ฏ Key Insight: Use a dummy head node and maintain a previous pointer to safely skip entire groups of duplicates in one pass, leveraging the sorted property for optimal O(n) performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code