DEV Community

Mubashir
Mubashir

Posted on

Remove Duplictes in sorted Linked List

In this task, I worked on removing duplicate nodes from a sorted linked list.
Since the list is already sorted, duplicate elements will always be next to each other, which makes the problem easier.

MY APPROACH
I created a function that takes the head of a sorted linked list and removes all duplicate nodes, returning the updated list

EXAMPLE
INPUT : 1->1->2->3->4->Null
output : 1->2->3->4

LOGIC IMPLEMENTED
Since the list is sorted:

  • I compared each node with its next node
  • If both values are the same → remove the duplicate
  • Otherwise → move to the next node
class Solution:
    def removeDuplicates(self, 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
Enter fullscreen mode Exit fullscreen mode

HOW IT WORKS:

  • Since duplicates are adjacent, we only need to check the next node
  • If duplicate is found, we skip it by changing pointers
  • This removes duplicates without creating a new list

Top comments (0)