In this task, I worked on removing duplicate elements from a sorted linked list.
Since the list is already sorted, duplicate values will always appear next to each other.
What I Did:
I created a function removeDuplicates that:
Takes the head of a linked list
Removes duplicate nodes
Returns the modified list with only unique elements
How I Solved It
Instead of using extra space , I used a simple pointer traversal.
Approach
I used one pointer:
curr → starts from the head and traverses the list
Logic Behind It
At each step:
Compare the current node with the next node
If both values are the same:
Skip the next node → curr.next = curr.next.next
Otherwise:
Move to the next node → curr = curr.next
How It Works
Because the list is sorted:
All duplicates are adjacent
So we only need to compare neighboring nodes
When a duplicate is found, we simply bypass it, effectively removing it from the list.
CODE:
def removeDuplicates(head):
current = head
while current and current.next:
if current.data == current.next.data:
# Skip duplicate node
current.next = current.next.next
else:
# Move to next node
current = current.next
return head
Top comments (0)