Removing duplicates from a linked list is a common problem that helps you understand pointer traversal and in-place modification.
๐ Problem Statement
Given the head of a sorted linked list, remove all duplicate elements so that each value appears only once.
Return the updated linked list.
๐ Example
Input:
2 โ 2 โ 2 โ 2
Output:
2
๐ง Intuition
Since the list is already sorted:
๐ Duplicate elements will always be next to each other
So we can:
- Compare current node with next node
- Skip duplicates by adjusting pointers
๐ Approach (Iterative)
Step-by-Step:
- Start from the head
- Traverse the list
- If current value equals next value:
-
Skip the next node
- Else:
Move forward
๐ป Python Code
```python id="dup1"
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
def delete_duplicates(head):
current = head
while current and current.next:
if current.val == current.next.val:
current.next = current.next.next # skip duplicate
else:
current = current.next
return head
---
๐งพ Dry Run
For:
2 โ 2 โ 2 โ 2
Steps:
* Compare first two โ same โ skip
* Compare next โ same โ skip
* Continue until only one node remains
Final:
2
---
โก Complexity
Time Complexity: O(n)
Space Complexity: O(1)
---
๐ฅ Why This Works
* Sorted property ensures duplicates are adjacent
* Only one traversal needed
* No extra space used
---
โ ๏ธ Edge Cases
* Empty list
* Single node
* All elements same
---
๐ Conclusion
This problem teaches:
* Pointer manipulation
* Efficient traversal
* In-place linked list operations
Top comments (0)