DEV Community

Manoj Kumar
Manoj Kumar

Posted on

Remove Duplicates from a Sorted Linked List โ€“ Python

๐Ÿงน Remove Duplicates from a Sorted Linked List โ€“ Python

Hi All,

Today I solved an important linked list problem: Removing duplicates from a sorted linked list.


๐Ÿ“Œ Problem Statement

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

๐Ÿ‘‰ Must be done:

  • In-place
  • Without using extra space

๐Ÿ” Examples

Example 1:

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

Output:

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

Example 2:

Input: 2 -> 2 -> 2 -> 2 -> 2
Enter fullscreen mode Exit fullscreen mode

Output:

2
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก Key Insight

๐Ÿ‘‰ Since the list is sorted:

  • Duplicate elements will always be adjacent

๐Ÿ’ก Approach

๐Ÿ”น Traverse and Compare

  • Start from head
  • Compare current node with next node
  • If same โ†’ skip next node
  • Else โ†’ move forward

๐Ÿง  Step-by-Step Logic

  1. Start with current = head
  2. While current and current.next exist:
    • If values are same:
      • Skip next node
    • Else:
      • Move to next node

๐Ÿ’ป Python Code

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


def removeDuplicates(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

๐Ÿ” Dry Run

For:

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

Steps:

  • Compare 2 & 2 โ†’ remove duplicate
  • Move to 4 โ†’ no duplicate
  • Move to 5 โ†’ no duplicate

Final:

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

๐Ÿ–ฅ๏ธ Sample Output

Input: 2 -> 2 -> 4 -> 5
Output: 2 -> 4 -> 5

Input: 2 -> 2 -> 2 -> 2 -> 2
Output: 2
Enter fullscreen mode Exit fullscreen mode

โšก Complexity Analysis

  • Time Complexity: O(n) โœ…
  • Space Complexity: O(1) โœ…

๐Ÿง  Why this is important?

  • Uses linked list traversal
  • Efficient in-place modification
  • Common interview question

โœ… Conclusion

This problem helped me understand:

  • Handling duplicates in sorted data
  • Pointer manipulation in linked lists
  • Writing clean in-place solutions

๐Ÿš€ Must-know problem for coding interviews!


Top comments (0)