Deep-copy a linked list whose nodes have a random pointer
Question
Each node of a singly linked list has value, next and random. random points to any node of the same list, or is None. Write copy_list(head). It returns a deep copy: new nodes with the same values, where every next and random points into the new list, never into the old one.
Example: the list 5 → 3 → 3, where the random of the first two nodes points to the last node. In the copy, both must point to the copy of the last node, and the two nodes with value 3 must stay separate.
class Node: def __init__(self, value, next_node=None, random=None): self.value, self.next, self.random = value, next_node, random def copy_list(head): ...
Show hints (3)
- "THE HARD PART"
Copying
nextis easy, because you meet the nodes in order. Butrandommay point to a node you haven't copied yet. How can you know its copy before you get there? - "TWO PASSES"
First pass: make one new node for every old node, without links. Second pass: set the links. By then every target already has its copy.
- "OLD TO NEW"
Keep a dict from each old node to its copy. Then
new.random = copies.get(old.random). Key by the node itself, not its value: two nodes can both hold 3.
Show checked explanation
Make two passes. The first creates one new node per old node and saves it in a dict, old node to copy. The second sets each copy's next and random from that dict. The keys are the node objects, so equal values never merge, and a shared target gets one copy. Time and extra space are O(n).
class Node: def __init__(self, value, next_node=None, random=None): self.value, self.next, self.random = value, next_node, random def copy_list(head): copies = {} # old node -> its copy node = head while node: copies[node] = Node(node.value) node = node.next for old, new in copies.items(): new.next = copies.get(old.next) new.random = copies.get(old.random) return copies.get(head) last = Node(3) new = copy_list(Node(5, Node(3, last, last), last)) print(new.random is new.next.random is new.next.next, new.random is not last)
True True
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Call the old nodes A (5), B (3) and C (3). The demo builds A → B → C, and both A and B have random pointing to C.
The first pass fills the dict:
| old | copy | next of copy | random of copy |
|---|---|---|---|
| A | A' | B' | C' |
| B | B' | C' | C' |
| C | C' | None | None |
The second pass fills the last two columns. For A it looks up copies[B] and copies[C], which already exist. That is the point of two passes: a random pointer can jump forward, and its target is ready anyway.
In the output, the first True means that A'.random, B'.random and the third new node are one object, C'. The shared target got one copy. The second True means C' is a new node, not the old C.
Three details matter.
- Identity, not value.
Nodedoesn't define__eq__, so a dict compares nodes by identity. B and C both hold 3, but they are two keys and get two copies. - Empty pointers.
Noneis never a key incopies, socopies.get(None)returnsNone. An emptyrandomstays empty, and so does thenextof the last node. - Loops. The code never follows
randomwhile it copies. If C'srandompointed to C itself, the second pass would just setC'.random = C'.
Each pass visits each node once, so the time is O(n). The dict adds O(n) extra space.
Common mistakes
- Copying
nextbut keeping the oldrandom. The copy then points back into the old list, and a change to an old node shows up through the copy. - Using the value as the dict key. B and C both hold 3, so they share one key, and the copy ends up with one 3-node where it needs two.
- Making a new node every time you follow a
randompointer. A and B both point to C, so you get two different copies of C instead of one shared node. - Copying recursively along
next. Python's default recursion limit is 1,000, so a list with a few thousand nodes raisesRecursionError. Loops have no such limit.
Follow-up questions
- "Can you do it without the dict?" Yes. Put each copy right after its old node: A, A', B, B', C, C'. Then the copy of
old.randomisold.random.next, so you can set everyrandomwithout a dict. A last pass splits the two lists and restores the oldnextpointers. Time stays O(n), and extra space drops to O(1). - "Why not just call
copy.deepcopy(head)?" It gets the shape right, becausedeepcopyremembers what it has copied, so shared targets stay shared. But it followsnextrecursively, and a list of 1,000 nodes already raisesRecursionError. The interviewer also wants to see the old-to-new mapping.
What a strong answer covers
Explains why random needs a second pass or a lookup. Keys the dict by node identity, and handles None, shared targets and a node that points to itself. Knows the weaving trick that needs no dict.
Open in interactive practice deck →