download

Deep-copy a linked list whose nodes have a random pointer

Algorithms~15 minReviewed 1 Nov 2026Free · No sign-in

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.

"CODE · PYTHON"
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)
  1. "THE HARD PART"

    Copying next is easy, because you meet the nodes in order. But random may point to a node you haven't copied yet. How can you know its copy before you get there?

  2. "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.

  3. "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).

"SOLUTION · PYTHON"
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)
"OUTPUT"
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:

oldcopynext of copyrandom of copy
AA'B'C'
BB'C'C'
CC'NoneNone

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. Node doesn'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. None is never a key in copies, so copies.get(None) returns None. An empty random stays empty, and so does the next of the last node.
  • Loops. The code never follows random while it copies. If C's random pointed to C itself, the second pass would just set C'.random = C'.

Each pass visits each node once, so the time is O(n). The dict adds O(n) extra space.

Common mistakes

  • Copying next but keeping the old random. 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 random pointer. 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 raises RecursionError. 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.random is old.random.next, so you can set every random without a dict. A last pass splits the two lists and restores the old next pointers. Time stays O(n), and extra space drops to O(1).
  • "Why not just call copy.deepcopy(head)?" It gets the shape right, because deepcopy remembers what it has copied, so shared targets stay shared. But it follows next recursively, and a list of 1,000 nodes already raises RecursionError. 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 →

Original OfferVibe question. Topic idea from Crushing the Technical Interview (Keith Henning, 2025); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.