Back to articles
REMOVING DUPLICATES FROM A SORTED LINKED LIST

REMOVING DUPLICATES FROM A SORTED LINKED LIST

via Dev.to BeginnersAbinaya Dhanraj

How I Understood Removing Duplicates from a Sorted Linked List When I first saw this problem, it looked tricky because linked lists don’t allow random access like arrays. After thinking carefully, I realized that for a sorted linked list, duplicates are always consecutive, making it easier to handle in-place. ** Problem** Given a sorted linked list, remove all duplicate nodes so that each element appears only once. Example: Python Input: 1 -> 1 -> 2 -> 3 -> 3 -> None Output: 1 -> 2 -> 3 -> None What I Noticed The key observations: The list is sorted, so duplicates are consecutive We only need to compare each node with its next node If duplicate → skip it by updating curr.next Else → move forward This allows in-place removal without extra space. ** What Helped Me** The algorithm is simple: Start with curr = head While curr.next is not None: If curr.data == curr.next.data → skip the next node (curr.next = curr.next.next) Else → move curr forward (curr = curr.next) Return head No addition

Continue reading on Dev.to Beginners

Opens in a new tab

Read Full Article
6 views

Related Articles