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.)
Variables
n=5
How to think about it
- A HashMap<orig, clone> gives O(n) time but O(n) extra space.
- Interleaving the clone node right after its original encodes the mapping in the list itself.
- Phase 2 can resolve any random with p.random.next.
- 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 1
deep clone{"values":[7,13,11,10,1],"random":[null,0,4,2,0]}
Example 2
null{"values":[],"random":[]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed