DEV Community

Padma Priya R
Padma Priya R

Posted on • Edited on

Remove Duplicates from a Sorted Linked List

Problem Statement

Given a singly linked list, remove all duplicate nodes so that only the first occurrence of each value remains.

Examples:

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

Output:
2 -> 4 -> 5

Input:
2 -> 2 -> 2 -> 2 -> 2

Output:
2

Constraints:

Number of nodes: 1 ≤ n ≤ 10^5
Node values: 1 ≤ data ≤ 10^5
Expected time complexity: O(n)
Expected space complexity: O(1)

Approach
Start from the head node.
Compare the current node with the next node.
If they are equal, skip the next node by updating current.next.
Otherwise, move to the next node.
Repeat until the end of the list.

Python Code

def removeDuplicates(head):
current = head
while current and current.next:
if current.data == current.next.data:
current.next = current.next.next # skip duplicate
else:
current = current.next
return head

Explanation

We use a pointer current to traverse the linked list.
For each node, we check if its data is equal to the data of the next node.
If yes, we skip the next node by pointing current.next to current.next.next.
Otherwise, we move current forward.
This ensures all duplicates are removed in one pass.

Top comments (0)