LeetCode 82. Remove Duplicates from Sorted List II

Description

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

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]

Example 2:

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

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.

Explanation

We can count the node value occurrences first and then remove those nodes with duplicated values.

Python Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        counter = {}

        dummy = ListNode(0)
        dummy.next = head
        
        
        while head != None:
            counter[head.val] = counter.get(head.val, 0) + 1            
            head = head.next
                        
        head = dummy.next
        prev = dummy
                
        while head != None:
            if counter[head.val] > 1:
                prev.next = head.next
            else:
                prev = head
            head = head.next
            
        return dummy.next
            
  • Time Complexity: O(N).
  • Space Complexity: O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *