DEV Community

Santhoshi Mary A
Santhoshi Mary A

Posted on

Remove Duplicates in Sorted Linked List

Problem Statement

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

Important:

The list is already sorted.
Do not use extra space.
Modify the list in-place.
Return the head of the updated list.
Example 1

Input:

2 -> 2 -> 4 -> 5

Output:

2 -> 4 -> 5

Explanation:
The value 2 appears twice. Since the list is sorted, duplicates are adjacent. We remove one occurrence.

Example 2

Input:

2 -> 2 -> 2 -> 2 -> 2

Output:

2

Explanation:
All elements are the same. We keep only one node and remove the rest.

Key Observation

Because the linked list is sorted, duplicate values will always appear next to each other.

That means we don’t need:

Extra data structures
Nested loops
Hashing

We can solve it using a single traversal.

Approach (Single Traversal)
Idea
Start from the head.
Compare the current node with its next node.
If both values are equal:
Skip the next node.
Otherwise:
Move forward.
Python Implementation
def removeDuplicates(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 (Step-by-Step)

Let’s take:

2 -> 2 -> 4 -> 5
Step 1:
curr = first 2
curr.data == curr.next.data → duplicate found
Skip next node

List becomes:

2 -> 4 -> 5
Step 2:
curr moves to 4
4 != 5 → move forward
Step 3:
curr moves to 5
End of list

Final Result:

2 -> 4 -> 5

Top comments (0)