CA 23 - Remove Duplicates in Sorted Linked List

Remove Duplicates from a Sorted Linked List

Given a singly linked list. The task is to remove duplicates (nodes with duplicate values) from the given list (if it exists).
Note: Try not to use extra space. The nodes are arranged in a sorted way.

Input:
LinkedList: 2->2->4->5
Output: 2 -> 4 -> 5
Explanation: In the given linked list 2 -> 2 -> 4 -> 5, only 2 occurs more than 1 time. So we need to remove it once.
Input:
LinkedList: 2->2->2->2->2
Output: 2
Explanation: In the given linked list 2 -> 2 -> 2 -> 2, 2 is the only element and is repeated 5 times. So we need to remove any four 2.

Expected Time Complexity : O(n)
Expected Space 
Complexity: O(1)

CODE:

    Here to remove the duplicates from the linked list, we will use a pointer and then use it to traverse and check if the next node to have same data, if so then we will change the ptr -> next to ptr->next->next thus duplicates are removed.


class Solution:
    def removeDuplicates(head):
    ptr = head

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

    return head

    

Comments

Popular posts from this blog

CA 04 - Two Sum & Sorted Two Sum

CA 05 - Reverse the array

CA 21 - Basic Select SQL Queries