Learn / Linked lists

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

MethodHowExtra memory
Hash mapfirst pass: map each original node to a new copy; second pass: set copy.next = map[x.next], copy.random = map[x.random]O(n)
Weavingput each copy right after its original, so copy(x) = x.next; then unweaveO(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 next pointers.
  • Stepping by one node in the weaving passes instead of two (original, copy, original, …).

Problems

0 of 1 solved

Check yourself

Why can't you set each copy's random pointer while you create the copies in one pass?

After weaving, each copy sits right after its original. What is the copy of node x's random target?

What must the last pass of the weaving method do besides building the copy list?