DEV Community

Christina Sharon S
Christina Sharon S

Posted on • Edited on

Remove Duplicates from a Sorted Linked List

Introduction

When working with linked lists, handling duplicates is a common task. This problem becomes easier when the list is already sorted because duplicate values will always appear next to each other.

Problem Statement

Given a sorted singly linked list remove all duplicate nodes so that each element appears only once.

Return the modified linked list.

Example

Input:

2 -> 2 -> 4 -> 5
Enter fullscreen mode Exit fullscreen mode

Output:

2 -> 4 -> 5
Enter fullscreen mode Exit fullscreen mode

Key Insight

Since the list is sorted:

  • Duplicate elements will be adjacent
  • So we only need to compare the current node with the next node

Approach

We traverse the linked list and:

  • If current value == next value then skip the next node
  • Else move forward

Steps

  1. Start from head
  2. While current and current.next exist:
  • If values are same then remove duplicate
  • Else move to next node

Python Implementation

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


def remove_duplicates(head):
    current = head

    while current and current.next:
        if current.val == current.next.val:
            current.next = current.next.next  # skip duplicate
        else:
            current = current.next

    return head
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Example

For:

2 -> 2 -> 4 -> 5
Enter fullscreen mode Exit fullscreen mode
  • Compare 2 and 2 duplicate so remove one
  • Move to 2 compare with 4 different
  • Continue till end

Final result:

2 -> 4 -> 5
Enter fullscreen mode Exit fullscreen mode

Key Points

  • Works because list is sorted
  • No extra space required
  • Simple pointer manipulation
  • Very common beginner problem

Conclusion

Removing duplicates from a sorted linked list is a straightforward problem once you understand how linked list pointers work. Since duplicates are adjacent we can solve it efficiently in a single pass.

Top comments (0)