The Runtime Theory
mediumleetcode#linked-list#hash-table

Copy List With Random Pointer

Deep-copy a linked list with random pointers in O(n) time using an interleaved clone-then-wire technique — no hash map required.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[[7,null],[13,0],[11,4],[10,2],[1,0]]

out[[7,null],[13,0],[11,4],[10,2],[1,0]]

in[[1,1],[2,1]]

out[[1,1],[2,1]]

in[[3,null],[3,0],[3,null]]

out[[3,null],[3,0],[3,null]]

Given a linked list where every node carries val, a next pointer, and a random pointer to an arbitrary node (or null), construct a deep copy — new nodes, identical structure. The machine cannot share nodes with the original, and random may point anywhere, even forward.

The key insight: a hash map of original→clone works, but there is an O(1)-space variant — interleave each clone directly after its original. Then every original's random target is immediately followed by its clone, so wiring the clone's random is a single pointer hop: clone.random = original.random.next.

Approach:

  1. Pass one: for each original node, insert a clone between it and its successor.
  2. Pass two: wire each clone's random via the interleaving trick.
  3. Pass three: unweave the list — restore original next links, extract clones.
python
def copy_random_list(head):
    node = head
    while node:
        clone = Node(node.val, node.next)
        node.next = clone
        node = clone.next
    node = head
    while node:
        if node.random:
            node.next.random = node.random.next
        node = node.next.next
    dummy = tail = Node(0)
    node = head
    while node:
        tail.next = node.next
        tail = tail.next
        node.next = tail.next
        node = node.next
    return dummy.next

Time: O(n), three passes. Space: O(n) for clones, O(1) auxiliary.

Trickiest edge case: random pointing to null — the wiring pass must guard with if node.random before dereferencing .next.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.