Remove Duplicates in Sorted Linked List

Published: (March 20, 2026 at 03:20 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to


⚠️ Collection Error: Content refinement error: Error: 429 429 Too Many Requests: you (bkperio) have reached your weekly usage limit, upgrade for higher limits: https://ollama.com/upgrade


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. I created a function removeDuplicates that: Takes the head of a linked list Removes duplicate nodes Returns the modified list with only unique elements Instead of using extra space , I used a simple pointer traversal. I used one pointer: curr → starts from the head and traverses the list 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

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

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. O(n) → traverse the list once O(1) → no extra space used Original: 1 → 1 → 2 → 3 → 3 → 4 → None After removing duplicates: 1 → 2 → 3 → 4 → None

0 views
Back to Blog

Related posts

Read more »