Remove Duplicates from Sorted List
Master this topic with zero to advance depth.
Remove Duplicates from Sorted List
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Visual Representation
List: 1 -> 1 -> 2 -> 3 -> 3
1. 1 == 1. 1.next points to 2.
2. 2 != 1. Move to 2.
3. 3 == 3. 3.next points to null.
Result: 1 -> 2 -> 3Examples
Level I: Iterative
Intuition
Since the list is sorted, nodes with the same value will be adjacent. Traverse the list, and if a node's value equals its next node's value, skip the next node.
Detailed Dry Run
1->1->2.
- head=1, next=1. Val 1 == 1. 1.next = 1.next.next = 2.
- head=1, next=2. Val 1 != 2. head=2.
- head=2, next=null. End.
⚠️ Common Pitfalls & Tips
Only works on sorted lists. For unsorted lists, a hash set would be needed.
Level II: Recursive
Intuition
The recursive approach checks the head and its next node. If they have the same value, it skips the current head and returns the result of the recursive call on the next node.
Detailed Dry Run
1->1->2.
- head=1, next=1. Val 1 == 1. Return deleteDuplicates(1.next).
- head=1, next=2. Val 1 != 2. head.next = deleteDuplicates(2). Return head.
- head=2, next=null. Return head.
⚠️ Common Pitfalls & Tips
Recursion depth is proportional to the number of nodes.
Level III: Iterative with Sentinel (Dummy Node)
Intuition
Using a dummy node isn't strictly necessary for this problem (since the head never changes), but it's a good practice to ensure consistency across all linked list problems.
- Initialize a
dummynode pointing tohead. - Iterate through the list using a
currpointer. - Compare
currwithcurr.nextand skip duplicates.
Detailed Dry Run
Dummy -> 1 -> 1 -> 2.
- curr = 1. curr.next = 1. Match. curr.next = 2.
- curr = 1. curr.next = 2. No match. curr = 2.
- curr = 2. curr.next = null. End.
⚠️ Common Pitfalls & Tips
Ensure the dummy value doesn't conflict with valid node values.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.