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
๐ŸŽญ VIP Guest List Quality ControlOriginal Guest List (Sorted):Aliceโœ“ UniqueBobโœ“ UniqueCarolโœ— DuplicateCarolโœ— DuplicateEveโœ“ UniqueSecurity Process:SecurityGuardDummy HeadprevAlicecurrWhen Duplicates Detected:CarolCarolSkip Entire Group!Final VIP List (Unique Names Only):AliceBobEve๐ŸŽ‰ Clean VIP List Ready!
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.
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 24
52.4K Views
High Frequency
~18 min Avg. Time
1.5K 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