138. Copy List with Random Pointer ๐
Last updated
Last updated
Difficulty: Medium
- Tags: Linked List
, Hashing
A linked list of length n
is given such that each node contains an additional random
pointer, which could point to any node in the list, or null
.
Construct a deep copy of the list. The deep copy should consist of exactly n
brand-new nodes, where each new node has its value set to the value of its corresponding original node. Both the next
and random
pointers of the new nodes should point to new nodes in the copied list, replicating the structure of the original list.
Return the head of the copied linked list.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
The number of nodes in the list is in the range [0, 1000]
.
-10^4 <= Node.val <= 10^4
Node.random
is null
or points to a node in the list.
We can solve this problem using three passes with a hash map to maintain the original node and its corresponding copied node.
Mapping Original Nodes to Copies:
Use a hash map to store each original node and its corresponding copied node.
Linking the next
and random
Pointers:
Traverse the original list again and set the next
and random
pointers of the copied nodes using the hash map.
Returning the Copied Head:
Return the copied node corresponding to the original head from the hash map.
O(n): We traverse the list twice โ once to create the nodes and once to set the pointers.
O(n): The hash map stores mappings for n
nodes.
You can find the full solution here.