CodeArchon

mediumLinked ListAmazonMicrosoftGoogle

Carbon Copy Chain

Each node has a next pointer AND a random pointer to any other node. Produce a deep copy without using extra per-node storage.

Given a linked list with an additional `random` pointer that can point to any node (or null), return a deep copy. O(1) extra space.

Choose approach

7
head
13
11
10
1
nil
1/5
Narrationstep 1 of 5

Original chain. (Random pointers aren't drawn here — treat them as a side-table.)

1def carbon_copy_chain(head):
2 if not head:
3 return None
4 p = head
5 while p:
6 copy = RandomNode(p.val, p.next, None)
7 p.next = copy
8 p = copy.next
9 p = head
10 while p:
11 p.next.random = p.random.next if p.random else None
12 p = p.next.next
13 clone_head = head.next
14 p = head
15 while p:
16 c = p.next
17 p.next = c.next
18 c.next = c.next.next if c.next else None
19 p = p.next
20 return clone_head
Variables
n=5

How to think about it

  1. A HashMap<orig, clone> gives O(n) time but O(n) extra space.
  2. Interleaving the clone node right after its original encodes the mapping in the list itself.
  3. Phase 2 can resolve any random with p.random.next.
  4. Phase 3 unweaves back into two independent chains in O(n).

Edge cases to catch in interview

  • Empty list → null.
  • random = null → set clone.random = null.
  • random points to self → still works (self → clone of self).

Examples

Example 1deep clone
{"values":[7,13,11,10,1],"random":[null,0,4,2,0]}
Example 2null
{"values":[],"random":[]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed