Remove Duplicates from Unsorted List
Given the head
of a unsorted linked list, delete all duplicates such that each element appears only once. Return the linked list as well.
Solutions
Approach 1 – Using hash table
Easy solution, use hash table to check duplicate item.
Steps
iterate through the linked list and adding each element to a hash table.
Whenwe discover a duplicate element, we remove the element and continue iterating.
Return
head
node.
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 2 – No Buffer Allowed
lf we don't have a buffer, we can iterate with two pointers: current which iterates through the linked list, and runner which checks all subsequent nodes for duplicates.
Steps
iterate through the linked list and adding each element to a hash table.
Whenwe discover a duplicate element, we remove the element and continue iterating.
Return
head
node.
Time Complexity: O(n²)
Auxiliary Space: O(1)
Last updated