Copy List with Random Pointer solution explained
To copy a linked list whose nodes also carry a random pointer, make one clone per original node and record the pairing in a hash map, then make a second pass that sets every clone's next and random through that map. That is O(n) time and O(n) extra memory. A space-saving variant weaves each clone directly after its original, sets the random pointers, then separates the two lists, using O(1) extra memory.
By Evin JohnPublished 6 min read
What you are asked to do
Each node has a value, a next pointer and an extra pointer, often called random, that may point to any node in the same list, to itself, or to nothing. Build a completely new list with the same values and the same pointer shape. No pointer in the copy may lead back into the original list, and the original must be left as it was.
| Original nodes (value, random) | What the copy must look like |
|---|---|
| (6, 2) → (1, none) → (8, 0) | Three new nodes; the first new node's random is the third new node, the third's random is the first new node |
| (4, 0) | One new node whose random points to itself |
| empty list | empty list |
| (2, 1) → (2, 1) | Equal values do not matter; both new randoms point to the second new node |
Why interviewers ask it
It tests whether you understand identity versus value. Copying values is trivial, but the random pointers must point to the right new node, and two nodes may hold the same value. It is also a gentle introduction to graph cloning: the same map-from-original-to-copy idea clones a whole graph with cycles.
Follow-ups
- Clone a general graph. BFS or DFS with the same original-to-clone map, creating clones when first seen.
- Do it in one pass. Create clones lazily from the map whenever next or random needs one that does not exist yet.
- Constant extra memory. The interleaving trick described below.
- Clone a binary tree with random pointers. The same two ideas applied to a tree walk.
A slow but honest first answer
Put the original nodes in an array and create clones in a parallel array. For each original with a random pointer, search the originals array for the node it points to and use that index in the clones array. Comparing by identity (not by value) keeps duplicates correct. The search makes it O(n²), which is the cue to replace it with a map.
def copy_with_random_slow(head):
originals = []
node = head
while node:
originals.append(node)
node = node.next
clones = [RNode(o.val) for o in originals]
for i, o in enumerate(originals):
clones[i].next = clones[i + 1] if i + 1 < len(clones) else None
if o.random is not None:
j = next(k for k, other in enumerate(originals) if other is o.random)
clones[i].random = clones[j]
return clones[0] if clones else NoneTwo passes with a map
Pass one creates a clone for every original and stores it in a dictionary keyed by the original node. Pass two sets each clone's next and random by looking up the originals' next and random in that dictionary. Putting None in the map as a key that maps to None removes every null check from the second pass.
class RNode:
def __init__(self, val, next=None, random=None):
self.val = val
self.next = next
self.random = random
def copy_with_random(head):
clone_of = {None: None}
node = head
while node: # pass 1: one clone per original
clone_of[node] = RNode(node.val)
node = node.next
node = head
while node: # pass 2: wire both pointers through the map
clone_of[node].next = clone_of[node.next]
clone_of[node].random = clone_of[node.random]
node = node.next
return clone_of[head]Interleaving: no map at all
Insert each clone right after its original, so the list reads A, A′, B, B′ and so on. Now the clone of any node X is simply X.next. That gives the random pointers for free: the clone's random is the original's random, then one step forward. Finally walk the woven list and split it into two, restoring every original next pointer as you go. The JavaScript version below does exactly that.
class RandomNode {
constructor(val, next = null, random = null) {
this.val = val;
this.next = next;
this.random = random;
}
}
function copyWithRandom(head) {
if (head === null) return null;
// 1. put each clone right after its original: A A' B B' ...
for (let node = head; node !== null; node = node.next.next) {
node.next = new RandomNode(node.val, node.next);
}
// 2. a clone's random is the node right after the original's random
for (let node = head; node !== null; node = node.next.next) {
node.next.random = node.random === null ? null : node.random.next;
}
// 3. unzip the two lists, restoring the original
const cloneHead = head.next;
for (let node = head; node !== null; node = node.next) {
const clone = node.next;
node.next = clone.next;
clone.next = clone.next === null ? null : clone.next.next;
}
return cloneHead;
}Step 2 must finish for every node before step 3 starts. If you unzip while still setting random pointers, some original.random.next values already point to the next original rather than to a clone.
Complexity
| Approach | Time | Extra memory | Touches the original? |
|---|---|---|---|
| Arrays with identity search | O(n²) | O(n) | No |
| Map from original to clone | O(n) | O(n) | No |
| Interleave, wire, unzip | O(n) | O(1) beyond the copy | Temporarily, then restored |
Cases to test
- An empty list.
- A node whose random points to itself.
- Random pointers that point backward, forward and to nothing in the same list.
- Several nodes with the same value, to catch code that matches by value.
- After copying, a check that the original's next and random pointers are unchanged.
Mistakes to avoid
- Pointing a clone's random at the original node instead of its clone.
- Keying the map by value, which breaks as soon as two nodes share a value.
- Setting random pointers in the same pass that creates clones, before forward clones exist.
- Leaving the original list woven together after the interleaving method.
How to explain it out loud
Fictional example
- Candidate
- The tricky part is that a random pointer can aim at a node I have not copied yet, so I will separate creating clones from wiring them.
- Candidate
- First pass: a clone per node, stored in a map keyed by the original node itself, not its value. Second pass: each clone's next and random come from the map. Linear time and linear memory.
- Candidate
- If memory matters, I can drop the map by placing each clone right after its original, so a clone is always original.next. Then I set randoms and unzip the lists, restoring the original.
Where to go next
Merge k Sorted Lists is another list problem where choosing the right helper structure decides the complexity. Add Two Numbers practices building a new list node by node.
Rehearsal help from Natively
This problem is mostly about explaining why identity matters. When you practice, Natively on Mac or Windows can read the prompt from a screenshot and sketch the map approach and the interleaving trick, which helps you check your plan after you have tried it yourself. The transcript of a spoken mock lets you confirm you said 'keyed by node, not by value' clearly. More on the AI interview assistant.
Questions people ask
How do you copy a list with random pointers?
First create a clone of every node and store original-to-clone pairs in a hash map. Then set each clone's next and random by looking up the original's next and random in the map.
Can you copy it without a hash map?
Yes. Insert each clone right after its original, set each clone's random to the original's random.next, then split the woven list back into two.
Why must the map be keyed by node and not by value?
Several nodes can share a value. Only the node's identity tells you which clone a random pointer should reach.
What is the time complexity?
O(n) for both methods. The map version uses O(n) extra memory; the interleaving version uses O(1) beyond the copy itself.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
