bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1836. Remove Duplicates From an Unsorted Linked List

1836. Remove Duplicates From an Unsorted Linked List

Leetcode Solutions

Two-Pass Approach with HashMap

  1. Initialize an empty HashMap to store the count of node values.
  2. Traverse the linked list from the head, incrementing the count for each value in the HashMap.
  3. Create a dummy node with a next pointer to the head of the list. This dummy node acts as a placeholder to handle edge cases where the head needs to be deleted.
  4. Initialize two pointers, prev and curr, where prev points to the dummy node and curr points to the actual head of the list.
  5. Traverse the list again using curr. For each node:
    • Check the count of the node's value in the HashMap.
    • If the count is greater than one, remove the node by setting prev.next to curr.next.
    • If the count is one, move prev to point to curr.
  6. Move curr to the next node in the list.
  7. After the traversal, set prev.next to null to terminate the list.
  8. Return the next node of the dummy node, which is the new head of the modified list.
UML Thumbnail

Single-Pass Approach with HashMap and Set

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...