DEV Community

Ashiq Omar
Ashiq Omar

Posted on

Remove Duplicates in Sorted Linked List

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:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def removeDuplicates(head):
    curr = head

    while curr and curr.next:
        if curr.val == curr.next.val:
            curr.next = curr.next.next  
        else:
            curr = curr.next

    return head
Enter fullscreen mode Exit fullscreen mode

Top comments (0)