DEV Community

Sandhya Steffy M
Sandhya Steffy M

Posted on

Remove Duplicates from a Sorted Linked List

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

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

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

Approach:
Since the linked list is sorted, duplicate values appear next to each other. We traverse the list using one pointer. Whenever the current node and next node have the same value, we skip the duplicate node by changing the next pointer.

Code:

class Node:
def init(self, data):
self.data = data
self.next = None

def removeDuplicates(head):
current = head

while current and current.next:
    if current.data == current.next.data:
        current.next = current.next.next
    else:
        current = current.next

return head
Enter fullscreen mode Exit fullscreen mode

Explanation:
The algorithm checks adjacent nodes. If two consecutive nodes contain the same value, the duplicate node is removed by adjusting the link. Since the list is sorted, this removes all duplicates in one traversal.

Time Complexity:
O(n)

Space Complexity:
O(1)

Top comments (0)