How I Understood Removing Duplicates from a Sorted Linked List
When I first saw this problem, it looked tricky because linked lists don’t allow random access like arrays.
After thinking carefully, I realized that for a sorted linked list, duplicates are always consecutive, making it easier to handle in-place.
** Problem**
Given a sorted linked list, remove all duplicate nodes so that each element appears only once.
Example:
Python
Input: 1 -> 1 -> 2 -> 3 -> 3 -> None
Output: 1 -> 2 -> 3 -> None
What I Noticed
The key observations:
The list is sorted, so duplicates are consecutive
We only need to compare each node with its next node
If duplicate → skip it by updating curr.next
Else → move forward
This allows in-place removal without extra space.
** What Helped Me**
The algorithm is simple:
Start with curr = head
While curr.next is not None:
If curr.data == curr.next.data → skip the next node (curr.next = curr.next.next)
Else → move curr forward (curr = curr.next)
Return head
No additional data structures are needed.
Code (Python)
Python
Node Class definition as provided in the challenge
class Node:
def init(self, data):
self.data = data
self.next = None
def removeDuplicates(head):
"""
Removes duplicate nodes from a sorted linked list in-place.
"""
if head is None:
return head
curr = head
while curr.next is not None:
if curr.data == curr.next.data:
# Skip duplicate
curr.next = curr.next.next
else:
# Move forward
curr = curr.next
return head
Example Usage
Python
Creating linked list: 1 -> 1 -> 2 -> 3 -> 3
head = Node(1)
head.next = Node(1)
head.next.next = Node(2)
head.next.next.next = Node(3)
head.next.next.next.next = Node(3)
Remove duplicates
new_head = removeDuplicates(head)
Print the list
curr = new_head
while curr:
print(curr.data, end=" -> ")
curr = curr.next
print("None")
Output:
Plain text
1 -> 2 -> 3 -> None
** Complexity**
Time: O(n) — traverse the list once
Space: O(1) — in-place, no extra space
What I Learned
This problem demonstrates that sorted property simplifies linked list operations:
Compare current and next nodes
Skip duplicates in-place
No extra storage needed
It’s an elegant example of pointer manipulation in linked lists.
Final Thought
At first, I thought removing duplicates might require extra structures.
Once I realized:
“Duplicates are consecutive — just compare current and next node”
…it became simple and efficient.
This is a classic linked list in-place algorithm.
Top comments (0)