Hi everyone!
Today I solved a linked list problem where we need to remove duplicate nodes from a sorted list. Since the list is already sorted, the solution becomes much easier.
Problem
Given a sorted linked list, remove duplicate nodes so that each element appears only once.
Example:
Input: 2 -> 2 -> 4 -> 5
Output: 2 -> 4 -> 5
My Approach
At first, I thought of using a set to track duplicates, but that would use extra space.
Then I realized:
Since the list is sorted, duplicates will always be next to each other
So we can solve it in-place.
Logic
Traverse the linked list
Compare current node with next node:
If equal → remove next node
Else → move forward
Code (Python)
def removeDuplicates(head):
curr = head
while curr and curr.next:
if curr.data == curr.next.data:
curr.next = curr.next.next
else:
curr = curr.next
return head
Time & Space Complexity
Time: O(n)
Space: O(1)
Key Insight
Because the list is sorted, duplicates are always adjacent — no need for extra memory.
What I Learned
Sorted property can simplify problems
Linked list manipulation requires careful pointer updates
In-place solutions are more efficient
Thanks for reading!
Feel free to share other approaches or improvements.
Top comments (0)