LeetCode 1836. Remove Duplicates From an Unsorted Linked List

Description

https://leetcode.com/problems/remove-duplicates-from-an-unsorted-linked-list/

Given the head of a linked list, find all the values that appear more than once in the list and delete the nodes that have any of those values.

Return the linked list after the deletions.

Example 1:

Input: head = [1,2,3,2]
Output: [1,3]
Explanation: 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with [1,3].

Example 2:

Input: head = [2,1,1,2]
Output: []
Explanation: 2 and 1 both appear twice. All the elements should be deleted.

Example 3:

Input: head = [3,2,2,1,3,2,4]
Output: [1,4]
Explanation: 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with [1,4].

Constraints:

  • The number of nodes in the list is in the range [1, 105]
  • 1 <= Node.val <= 105

Explanation

We can first iterate the linked list to count the value occurrences. Then iterate again on the linked list, if the node value is not duplicated, append that value to a new linked list.

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 deleteDuplicatesUnsorted(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
        
        
        new_dummy = ListNode(0)
        new_head = new_dummy
        
        while head != None:            
            if counter[head.val] > 1:
                pass
            else:
                new_head.next = ListNode(head.val)
                new_head = new_head.next
                
            head = head.next        
        
        return new_dummy.next
  • Time Complexity: O(N).
  • Space Complexity: O(N).

Leave a Reply

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