Skip to content

1836. Remove Duplicates From an Unsorted Linked List 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  ListNode* deleteDuplicatesUnsorted(ListNode* head) {
    ListNode dummy(0, head);
    unordered_map<int, int> count;

    for (ListNode* curr = head; curr; curr = curr->next)
      ++count[curr->val];

    ListNode* curr = &dummy;

    while (curr != nullptr) {
      while (curr->next && count.contains(curr->next->val) &&
             count[curr->next->val] > 1)
        curr->next = curr->next->next;
      curr = curr->next;
    }

    return dummy.next;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public ListNode deleteDuplicatesUnsorted(ListNode head) {
    ListNode dummy = new ListNode(0, head);
    Map<Integer, Integer> count = new HashMap<>();

    for (ListNode curr = head; curr != null; curr = curr.next)
      count.merge(curr.val, 1, Integer::sum);

    ListNode curr = dummy;

    while (curr != null) {
      while (curr.next != null && count.containsKey(curr.next.val) && count.get(curr.next.val) > 1)
        curr.next = curr.next.next;
      curr = curr.next;
    }

    return dummy.next;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def deleteDuplicatesUnsorted(self, head: ListNode) -> ListNode:
    dummy = ListNode(0, head)
    count = collections.Counter()

    curr = head
    while curr:
      count[curr.val] += 1
      curr = curr.next

    curr = dummy

    while curr:
      while curr.next and curr.next.val in count and count[curr.next.val] > 1:
        curr.next = curr.next.next
      curr = curr.next

    return dummy.next