A linked list of length n is given where each node also has a random pointer which could point to any node in the list or null. Construct a deep copy of the list — brand new nodes with identical structure. The new nodes must not share memory with the original list.
[[7,null],[13,0],[11,4],[10,2],[1,0]][[7,null],[13,0],[11,4],[10,2],[1,0]][[1,1],[2,1]][[1,1],[2,1]]new Node(curr.val) and store map[curr] = copy. Move curr = curr.next.curr = head. Set map[curr].next = map[curr.next].map[curr].random = map[curr.random]. Both targets guaranteed to exist.map[head] — the head of the deep-copied list.
Random pointers can jump backwards or forwards — even to the tail from the head. In a single pass, when we try to wire copy.random, the target copy node might not have been created yet.
Pass 1 pre-creates every copy node upfront (no pointers yet). Pass 2 can then safely look up any target via map[orig.random] — it is guaranteed to already exist in the map.
A hash map from each old node to its copy works in two passes. But it uses O(n) extra space.
First, insert each copy right after its original, so the list alternates old and new. Then each copy's random is the original's random dot next. Finally, split the list back into the original and the copy.
Put each copy right after its original. Then the copy of a node's random is just random dot next.
Run the animation above on your own input, or watch the 1:30 video explanation of Copy List with Random Pointer with a dry run and Java code.