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.