Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1836.html

1836. Remove Duplicates From an Unsorted Linked List

Level

Medium

Description

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:

Image text

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:

Image text

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

Output: []

Explanation: 2 and 1 both appear twice. All the elements should be deleted.

Example 3:

Image text

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, 10^5]
  • 1 <= Node.val <= 10^5

Solution

Loop over the linked list and use a hash map to store each value’s number of occurrences. Then create a dummy head before head. Starting from the dummy head, loop over the linked list again and remove the nodes that have values with occurrences greater than 1. Finally, return the node right after the dummy head.

  • /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode deleteDuplicatesUnsorted(ListNode head) {
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            ListNode temp = head;
            while (temp != null) {
                int val = temp.val;
                map.put(val, map.getOrDefault(val, 0) + 1);
                temp = temp.next;
            }
            ListNode dummyHead = new ListNode(0);
            dummyHead.next = head;
            temp = dummyHead;
            while (temp.next != null) {
                ListNode next = temp.next;
                int nextVal = next.val;
                if (map.get(nextVal) > 1)
                    temp.next = next.next;
                else
                    temp = temp.next;
            }
            return dummyHead.next;
        }
    }
    
    ############
    
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode deleteDuplicatesUnsorted(ListNode head) {
            Map<Integer, Integer> cnt = new HashMap<>();
            for (ListNode cur = head; cur != null; cur = cur.next) {
                cnt.put(cur.val, cnt.getOrDefault(cur.val, 0) + 1);
            }
            ListNode dummy = new ListNode(0, head);
            for (ListNode pre = dummy, cur = head; cur != null; cur = cur.next) {
                if (cnt.get(cur.val) > 1) {
                    pre.next = cur.next;
                } else {
                    pre = cur;
                }
            }
            return dummy.next;
        }
    }
    
  • // OJ: https://leetcode.com/problems/remove-duplicates-from-an-unsorted-linked-list/
    // Time: O(N)
    // Space: O(N)
    class Solution {
    public:
        ListNode* deleteDuplicatesUnsorted(ListNode* head) {
            unordered_map<int, int> cnt;
            for (auto p = head; p; p = p->next) cnt[p->val]++;
            ListNode dummy, *tail = &dummy;
            while (head) {
                auto node = head;
                head = head->next;
                if (cnt[node->val] == 1) {
                    tail->next = node;
                    tail = node;
                }// else delete node; // If I uncomment this code, I'll get heap-use-after-free error. Why?
            }
            tail->next = nullptr;
            return dummy.next;
        }
    };
    
  • # 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:
            cnt = Counter()
            cur = head
            while cur:
                cnt[cur.val] += 1
                cur = cur.next
            dummy = ListNode(0, head)
            pre, cur = dummy, head
            while cur:
                if cnt[cur.val] > 1:
                    pre.next = cur.next
                else:
                    pre = cur
                cur = cur.next
            return dummy.next
    
    
    
  • /**
     * Definition for singly-linked list.
     * type ListNode struct {
     *     Val int
     *     Next *ListNode
     * }
     */
    func deleteDuplicatesUnsorted(head *ListNode) *ListNode {
    	cnt := map[int]int{}
    	for cur := head; cur != nil; cur = cur.Next {
    		cnt[cur.Val]++
    	}
    	dummy := &ListNode{0, head}
    	for pre, cur := dummy, head; cur != nil; cur = cur.Next {
    		if cnt[cur.Val] > 1 {
    			pre.Next = cur.Next
    		} else {
    			pre = cur
    		}
    	}
    	return dummy.Next
    }
    
  • /**
     * Definition for singly-linked list.
     * class ListNode {
     *     val: number
     *     next: ListNode | null
     *     constructor(val?: number, next?: ListNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.next = (next===undefined ? null : next)
     *     }
     * }
     */
    
    function deleteDuplicatesUnsorted(head: ListNode | null): ListNode | null {
        const cnt: Map<number, number> = new Map();
        for (let cur = head; cur; cur = cur.next) {
            const x = cur.val;
            cnt.set(x, (cnt.get(x) ?? 0) + 1);
        }
        const dummy = new ListNode(0, head);
        for (let pre = dummy, cur = head; cur; cur = cur.next) {
            if (cnt.get(cur.val)! > 1) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
        }
        return dummy.next;
    }
    
    

All Problems

All Solutions