Problem Description
Given the head of a linked list, remove all nodes that contain values appearing more than once. Only values that occur exactly once should remain in the linked list.
Key Insights
- A first pass through the linked list can be used to count the frequency of each value.
- Using a hash table (or dictionary) for counting frequencies supports O(n) time access.
- A dummy node simplifies edge cases (such as updates at the head) when deleting nodes.
- In a second pass, build the resulting list by skipping nodes with a frequency greater than 1.
Space and Time Complexity
Time Complexity: O(n) - We traverse the list twice (once for counting and once for filtering). Space Complexity: O(n) - A hash table stores counts for up to n unique values.
Solution
We first traverse the linked list to count the occurrence of each node's value using a hash table. After obtaining the frequency of every value, we use a dummy node to start building the new linked list. We traverse again, and if a node's value has a frequency of 1, we attach it to the new list; otherwise, we skip it. This two-pass approach ensures that all nodes with duplicate values are removed while handling edge cases (like removing the head node) gracefully.