December 18, 2021

Remove Duplicates from Sorted List II

Problem Statement: Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.


Example 1:

Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.



Leetcode Difficulty: Medium

Code:
    def deleteDuplicates(self, head):
        """
        head: ListNode
        return: ListNode
        """
        
        curr=head
        tmp=ListNode(-1, head)
        prev=tmp
        
        while curr:
            
            if curr.next and curr.val==curr.next.val:              
                while curr.next and curr.val==curr.next.val:
                    curr=curr.next
                prev.next=curr.next
            else:
                prev = prev.next
            
            curr=curr.next
            
        return tmp.next
Thought Process / Explanation:
It's all about adjusting pointers by making the adjacent comparisons. Need to take care of one special case, when all elements are the same. We define a dummy node for that and do a final return as per that.


Thank You!