Copy with random pointer
Deep-copying a list whose nodes also point to random other nodes needs a way to find, for any original node, its copy. A hash map from original to copy is the simple way. Weaving each copy right after its original does the same with O(1) extra memory.
How to recognise it
- Nodes have an extra pointer to any node (or null), and the question asks for a deep copy.
- The copy must not share any node with the original.
- The same idea appears when copying graphs, where each old node maps to its new node.
The idea in one picture
Photocopying a set of index cards is easy until the cards say "see card 7". Each copy must point to the copy of card 7, not the original. So you need, for every original card, a way to find its copy.
Two ways to find a node's copy
| Method | How | Extra memory |
|---|---|---|
| Hash map | first pass: map each original node to a new copy; second pass: set copy.next = map[x.next], copy.random = map[x.random] | O(n) |
| Weaving | put each copy right after its original, so copy(x) = x.next; then unweave | O(1) |
Template: weaving
for each original x: insert copy(x) right after x
for each original x: if x.random: x.next.random = x.random.next
for each original x:
c = x.next
x.next = c.next # restore the original
append c to the copy list
Common mistakes
- Pointing a copy's random at the original node, which shares nodes between the lists.
- Forgetting to restore the original's
nextpointers. - Stepping by one node in the weaving passes instead of two (original, copy, original, …).
Problems
- Copy List with Random Pointermediumguide ready