๐งน Remove Duplicates from a Sorted Linked List โ Python
Hi All,
Today I solved an important linked list problem: Removing duplicates from a sorted linked list.
๐ Problem Statement
Given a sorted singly linked list, remove all duplicate nodes such that each element appears only once.
๐ Must be done:
- In-place
- Without using extra space
๐ Examples
Example 1:
Input: 2 -> 2 -> 4 -> 5
Output:
2 -> 4 -> 5
Example 2:
Input: 2 -> 2 -> 2 -> 2 -> 2
Output:
2
๐ก Key Insight
๐ Since the list is sorted:
- Duplicate elements will always be adjacent
๐ก Approach
๐น Traverse and Compare
- Start from head
- Compare current node with next node
- If same โ skip next node
- Else โ move forward
๐ง Step-by-Step Logic
- Start with
current = head - While
currentandcurrent.nextexist:- If values are same:
- Skip next node
- Else:
- Move to next node
- If values are same:
๐ป Python Code
class ListNode:
def __init__(self, val=0):
self.val = val
self.next = None
def removeDuplicates(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 -> 4 -> 5
Steps:
- Compare 2 & 2 โ remove duplicate
- Move to 4 โ no duplicate
- Move to 5 โ no duplicate
Final:
2 -> 4 -> 5
๐ฅ๏ธ Sample Output
Input: 2 -> 2 -> 4 -> 5
Output: 2 -> 4 -> 5
Input: 2 -> 2 -> 2 -> 2 -> 2
Output: 2
โก Complexity Analysis
- Time Complexity: O(n) โ
- Space Complexity: O(1) โ
๐ง Why this is important?
- Uses linked list traversal
- Efficient in-place modification
- Common interview question
โ Conclusion
This problem helped me understand:
- Handling duplicates in sorted data
- Pointer manipulation in linked lists
- Writing clean in-place solutions
๐ Must-know problem for coding interviews!
Top comments (0)