The “Copy List with Random Pointer” problem asks you to create a deep copy of a special linked list. Each node in the list contains:
val
– the integer value of the nodenext
– a pointer to the next node in the listrandom
– a pointer to any node in the list (or null)
A deep copy means all the nodes should be newly created, and none of them should point to any node from the original list. All connections, including both next
and random
pointers, must be preserved.
This problem is a classic example of advanced linked list manipulation. It requires understanding how to duplicate both direct and arbitrary references between nodes. It builds important intuition for working with complex data structures like graphs or object graphs.
The simplest and most reliable way to solve this problem is to use a hash map (dictionary) that maps each original node to its corresponding copied node.
null
, return null
.oldToNew
to store mappings from original nodes to copied nodes.next
and random
pointers for each copied node using the hash map:
copy.next = oldToNew[original.next]
copy.random = oldToNew[original.random]
oldToNew[head]
as the new head of the deep-copied list.Consider the list:
First pass creates new nodes: A′, B′, C′.
Second pass wires:
Time Complexity: O(n), where n
is the number of nodes in the list. We perform two passes through the list.
Space Complexity: O(n) for the hash map that stores original-to-copy mappings.
The “Copy List with Random Pointer” problem is a great test of your understanding of deep copying, hashing, and reference manipulation. While the use of a hash map is straightforward, it lays the groundwork for more space-efficient solutions and shows how auxiliary data structures can simplify complex linked list operations.