Problem Description
Given the head of a linked list where each node contains an extra pointer, random, that can point to any node in the list or null, create a deep copy of the list. The new list must have exactly n brand new nodes where both the next and random pointers replicate the original list’s structure without pointing to nodes in the original list.
Key Insights
- Use a hash map (or dictionary) to map each original node to its corresponding copy.
- Perform two passes: the first to create a copy of each node, and the second to assign the next and random pointers using the hash map.
- An alternative interleaving approach exists but using a hash table is typically more straightforward.
Space and Time Complexity
Time Complexity: O(n) – Each node is processed a constant number of times. Space Complexity: O(n) – A hash map is used to store the mapping from original nodes to their copies.
Solution
The solution uses a two-pass algorithm. In the first pass, we iterate through the original list and for each node, create a new node (deep copy) while saving the mapping between the original and copy in a hash table. In the second pass, we iterate over the original list again to assign the next and random pointers of the new nodes using the previously built map. This guarantees that every pointer in the copied list corresponds to a new node and not the original.