Scrivio Interview library
Linked listsLinked listsReported 45 times · 17 min read · updated 15 November 2026

Make a deep copy of a linked list where each node also has a random pointer.

1What it means to copy a list that has random pointers

Picture five students standing in a line in the school hall, each with a hand on the shoulder of the student in front, so the line can be followed from first to last. Each student also points at one study buddy, who can be anyone in the line, even themselves, or nobody. The teacher wants an exact second class of five new students in another room, standing in the same order and pointing in the same pattern. The catch is that every new student must point at a new student, never at someone back in the hall.

That is our problem. The line is a linked list and each student is a node. A node here has three parts: a value, a next reference saying which node comes after it, and a random reference that may refer to any node, to the node itself, or to nothing, which Java writes as null. A reference is simply a variable that names a node, like a hand on a shoulder or a pointing finger.

A deep copy is a brand new list of brand new nodes with the same values, in which every next and random reference refers to another copy. If a copy's random refers back to an original node, the copy prints correctly but is wrong, because changes to the original show through it. That half-done copy is called a shallow copy, and avoiding it is the point of the question.

Our example holds 7, 13, 11, 10 and 1 in that order. Their randoms: 7 points to nothing, 13 to 7, 11 to 1, 10 to 11, and 1 to 7. We write a copy with a dash, so 13' is the copy of 13. The answer is a new list 7', 13', 11', 10', 1', where 13' points to 7', 11' to 1', 10' to 11' and 1' to 7'.

PictureThe example list and its random references

The arrows are the next references. The random references are listed beside the list, because they can point anywhere.

  1. 71311101
    7.random
    null
    13.random
    7
    11.random
    1
    10.random
    11
    1.random
    7

    1The arrows show next: 7 -> 13 -> 11 -> 10 -> 1. The panel shows each random. Our copy must repeat all of it using only new nodes.

What to assume

Can values repeat?
Yes, so we never find a node by its value.
Can the list be empty?
Yes, and its copy is null.
May we change the input while we work?
We assume yes, if we put it back exactly.
How long can it be?
Long enough that recursion, one waiting call per node, could run out of stack.

This looks frightening because randoms can point backwards, forwards or at themselves. It is smaller than it looks. Copying the values and next references is the easy part, the same as for any list. The only real question is this: when an original node's random is, say, node 1, how do we find node 1's copy? Answer that quickly and the problem is solved.

A careful candidate asks a few questions first. Can values repeat? Yes, so we never find a node by its value. Can the list be empty? Yes, and its copy is null. May we change the input while we work? We assume yes, if we put it back exactly. How long can it be? Long enough that recursion, one waiting call per node, could run out of stack.

2How to recognise this kind of linked list problem

A beginner usually walks the list once, copying each node and setting the copy's next and random on the spot. For next this works, because the next copy is the one we are about to make. For random it breaks down, as the next section shows: a random may point to a node we have not reached, whose copy does not exist yet.

So let us read the clues one at a time. The first is the words deep copy. Copying has two jobs, making new nodes and connecting them, and for an ordinary list we do both in one walk without noticing. Here connections can go anywhere, so the jobs must be separated: make every node first, then connect them when every target exists.

The second clue is the word random. A reference can jump to any node, so when we connect a copy we will hold an original node and need its copy. That trip from original to copy must be quick, ideally one step, or connecting becomes slow.

Together the clues place this in the linked lists pattern family, with a plain technique: make every copy first, then connect the copies, keeping a quick way from each original to its copy. A HashMap gives that quick way, and the cleverer solution stores it inside the list itself. The rule to carry to other problems: whenever you copy something whose references can point anywhere, a list with randoms, a tree with parent references or a graph, give each original exactly one copy and a fast way to find it, and connect only after the copies exist.

Some patterns look similar but do not fit. Fast and slow pointers find a middle or a loop but copy nothing. Reversing a list rewires links in place, but here the input must end up unchanged. Cloning a graph with breadth-first search is the general form of this problem, and the FAQs return to it.

3The honest first attempt, remembering positions

Let us first try the single walk, because seeing exactly where it fails tells us what we need. We walk the list, and at each node we make its copy and link it behind the previous copy. The picture follows that walk and stops where it gets stuck.

Step throughWhy one walk is not enough

Top row: the original list. Bottom row: the copies made so far by a single walk.

  1. 713111017'
    7.random
    null
    7'.random
    null, fine

    1We make 7' for 7. 7 has no random, so 7' needs none, and so far the single walk is going well.

  2. 713111017'13'
    13.random
    7
    copy of 7
    7', but where is it?

    2We make 13' and link 7' to it. 13.random is 7, and 7' does exist, but holding only the original 7, nothing tells us where 7' is.

  3. 713111017'13'11'
    11.random
    1
    copy of 1
    not made yet

    3We make 11'. 11.random is node 1, further down the line, and 1' has not been made yet, so the single walk is stuck.

Java
static Node copyByPosition(Node head) {
List<Node> originals = new ArrayList<>(), copies = new ArrayList<>();
for (Node cur = head; cur != null; cur = cur.next) { // first walk: make every copy
originals.add(cur);
copies.add(new Node(cur.val)); // same position in both lists
}
for (int i = 0; i < copies.size(); i++) { // second walk: connect them
if (i + 1 < copies.size()) copies.get(i).next = copies.get(i + 1);
Node r = originals.get(i).random;
if (r != null) copies.get(i).random = copies.get(originals.indexOf(r)); // a search every time
}
return copies.isEmpty() ? null : copies.get(0);
}

So the brute force that does work splits the walk in two. The first walk puts every original into one ArrayList and its new copy into a second at the same position, so the copy of the node at position k is at position k in the copies list. The second walk links each copy to the next, and for a random it finds the target's position among the originals with indexOf and takes the copy at that position.

Let us do it by hand. The first walk fills originals with 7, 13, 11, 10, 1 and copies with 7', 13', 11', 10', 1'. Then 7 has no random. The random of 13 is 7, which indexOf finds at position 0 after one comparison, so 13' points at 7'. The random of 11 is 1, found at position 4 after five comparisons, so 11' points at 1'. The random of 10 is 11, found after three, and that of 1 is 7, found after one.

Now count. The two walks visit five nodes each, and the searches add 1 + 5 + 3 + 1 = 10 comparisons. In a long list, indexOf may read the whole list for every node, about n times n comparisons, so the time is O(n^2), read as order n squared, and the two lists take O(n) extra memory, called space. 100,000 nodes could need ten billion comparisons.

Where is the waste? When we made each copy, we knew exactly which original it belonged to, then threw that away and searched again for every random. We need to remember, for each original, where its copy is, in a form we can reach in one step.

4Getting to the woven list, one observation at a time

The first way to remember is a HashMap, which works like the index at the back of a book: give it a word and it gives you the page at once. The key is an original node and the value its copy. The first walk stores map.put(original, copy). The second sets map.get(X).next = map.get(X.next) and map.get(X).random = map.get(X.random) for each original X, and since map.get(null) returns null, no special cases are needed. That is O(n) time and the answer to give first in an interview, because it is short and clearly correct. Its price is O(n) extra space.

Now the question a beginner asks at the hard step: can we find a copy in one step without any map? Every original already has a slot right next to it, its next reference. What if each copy stood directly behind its original in the same line? Then the copy of any node X would be X.next.

So the first pass weaves the copies in. For each original we make its copy, point the copy at the original's old next, and point the original at the copy, so 7, 13, 11, 10, 1 becomes 7, 7', 13, 13', 11, 11', 10, 10', 1, 1'. In the school hall, each new student now stands right behind the student they copy.

The second pass rests on one line, X.next.random = X.random.next. Read it a piece at a time. X.next is the copy of X, standing right behind it. X.random is the original that X points to. X.random.next stands right behind that one, so it is its copy. The line says: make my copy point at the copy of the node I point to. For 11, whose random is 1, it sets 11'.random to 1.next, which is 1'. When X.random is null we skip the line, because null has no next.

Why not set the randoms while weaving? Because when we weave 11, node 1 has no copy behind it yet, so 1.next is still null rather than 1', and 11' would get a null random. Randoms can be set only once every copy exists.

The third pass separates the lists. Each original takes back its old next, which is now its copy's next, and each copy joins the end of a new list that starts with a dummy node, a spare placeholder that saves a special case for the first copy. The mistake beginners make most often is to stop after the second pass and return head.next, a list with the originals still woven through it.

5Watching the three passes on the example

The picture runs all three passes on our five nodes, with frames taken from the Java method printing after each step. Copies have a dash and arrows are next references. Randoms would cross everything as arrows, so the panel lists them, and in the second pass the marked nodes are the three that X.next.random = X.random.next touches.

In the third pass the first row holds originals already separated, the second the copies already chained, and the third the still woven rest.

Step throughWeaving, setting randoms and splitting 7, 13, 11, 10, 1

A dash marks a copy. Arrows are next references; the panel lists the random references.

  1. 71311101cur
    7.random
    null
    13.random
    7
    11.random
    1
    10.random
    11
    1.random
    7

    1Before the first pass we have the five original nodes. cur starts on the head, 7, and the panel lists where each random reference points.

  2. 77'1311101cur
    pass
    1, weaving
    just made
    7'
    cur
    13

    2Pass one makes 7', points it at 13, and points 7 at 7'. Now 7' stands right behind 7, and cur jumps two places to 13.

  3. 77'1313'1111'1010'11'
    pass
    1 finished
    copy of X
    X.next
    copy randoms
    none set yet

    3Pass one has woven a copy behind every original. The copy of any original X is now simply X.next, so we need no map.

  4. 77'1313'1111'1010'11'cur
    pass
    2, randoms
    cur
    7
    7.random
    null, skip
    set so far
    7':null

    4Pass two starts on 7. Its random is null, so we skip it and 7' keeps a null random. cur jumps two places to 13.

  5. 77'1313'1111'1010'11'currandom
    pass
    2, randoms
    cur
    13
    rule
    13'.random = 7.next = 7'
    set so far
    7':null 13':7'

    5On 13, whose random is 7, the line sets 13'.random = 7.next. The node behind 7 is 7', so 13' now points at 7', a copy.

  6. 77'1313'1111'1010'11'currandom
    pass
    2, randoms
    cur
    11
    rule
    11'.random = 1.next = 1'
    set so far
    7':null 13':7' 11':1'

    6On 11, whose random is 1, the line sets 11'.random = 1.next, which is 1'. One step, even though 1 is far down the line.

  7. 77'1313'1111'1010'11'
    pass
    2 finished
    copy randoms
    7':null 13':7' 11':1' 10':11' 1':7'

    7The same line runs on 10, whose random is 11, giving 10' -> 11', and on 1, whose random is 7, giving 1' -> 7'. Every copy's random is set.

  8. 7cur7'tail1313'1111'1010'11'
    pass
    3, splitting
    7.next
    13 again
    new list
    7'

    8Pass three gives 7 its old next, 13, and adds 7' to the new list. For a moment both 7 and 7' still lead into the woven rest on the third row.

  9. 713cur7'13'tail1111'1010'11'
    pass
    3, splitting
    13.next
    11 again
    new list
    7', 13'

    9Next, 13 takes back 11, and tail.next = 13' links 7' to 13'. The first two pairs are now fully separated.

  10. 71311101head7'13'11'10'1'return
    original
    restored
    copy randoms
    7':null 13':7' 11':1' 10':11' 1':7'

    10Pass three has finished. The first row is the original list, exactly as it was, and the second row is the deep copy we return.

Let us read the important frames back. After the first insertion the line reads 7, 7', 13, and cur jumps two places, from 7 to 13, because the node behind each original is now its copy. After five insertions every original has its copy behind it.

The fifth frame is the heart of the method. On 13, whose random is 7, the copy of 13 is 13' and the copy of 7 is the node behind 7, 7', so 13'.random becomes 7'. The sixth frame gives 11'.random = 1' in one step, though 1 is far down the line.

In the last frames the lists come apart a pair at a time. After the first split, 7 points to 13 again and 7' starts the new list, and for a moment both still lead into the woven rest until the next split points 7' at 13'. At the end, the first row is the original, unchanged, and the second is the deep copy.

6The complete Java program

Here is the full program. build makes a list from values and random positions, and show prints each node as its value and the position of its random target. main copies our example, prints the original again, checks that the copy shares no node with it, and copies a one-node list whose random points to itself and an empty list.

Java
import java.util.*;
public class CopyRandomList {
static class Node {
int val; Node next, random;
Node(int val) { this.val = val; }
}
// Weave copies between the originals, set randoms, then unweave. O(n) time, O(1) extra space.
static Node copy(Node head) {
for (Node cur = head; cur != null; cur = cur.next.next) {
Node clone = new Node(cur.val);
clone.next = cur.next; // A -> A' -> B -> B' ...
cur.next = clone;
}
for (Node cur = head; cur != null; cur = cur.next.next) {
if (cur.random != null) cur.next.random = cur.random.next; // the copy of my random
}
Node dummy = new Node(0), tail = dummy;
for (Node cur = head; cur != null; cur = cur.next) {
Node clone = cur.next;
cur.next = clone.next; // give the original its old next back
tail.next = clone; // add the copy to the new list
tail = clone;
}
return dummy.next;
}
static Node build(int[] vals, Integer[] randomIdx) {
Node[] nodes = new Node[vals.length];
for (int i = 0; i < vals.length; i++) nodes[i] = new Node(vals[i]);
for (int i = 0; i < vals.length; i++) {
if (i + 1 < vals.length) nodes[i].next = nodes[i + 1];
if (randomIdx[i] != null) nodes[i].random = nodes[randomIdx[i]];
}
return vals.length == 0 ? null : nodes[0];
}
// Print each node as [value, index of its random node].
static String show(Node head) {
List<Node> order = new ArrayList<>();
for (Node n = head; n != null; n = n.next) order.add(n);
List<String> parts = new ArrayList<>();
for (Node n : order) parts.add("[" + n.val + "," + (n.random == null ? "null" : order.indexOf(n.random)) + "]");
return parts.toString();
}
public static void main(String[] args) {
Node head = build(new int[] {7, 13, 11, 10, 1}, new Integer[] {null, 0, 4, 2, 0});
Node clone = copy(head);
System.out.println(show(clone)); // [[7,null], [13,0], [11,4], [10,2], [1,0]]
System.out.println(show(head)); // [[7,null], [13,0], [11,4], [10,2], [1,0]]
System.out.println(clone != head && clone.next.random != head); // true
Node self = build(new int[] {5}, new Integer[] {0});
System.out.println(show(copy(self))); // [[5,0]]
System.out.println(copy(null)); // null
}
}

Let us read copy in the order it runs. The first loop weaves. For each original cur it makes clone, points clone.next at cur.next, and only then points cur.next at clone. The order matters: writing cur.next = clone first would lose the rest of the list. The loop steps with cur = cur.next.next, jumping over the new clone.

The second loop also steps by two, visiting only originals, and cur.next.random = cur.random.next gives each copy its random.

The third loop keeps tail on the last node of the new list. For each original cur, clone is the node behind it; cur.next = clone.next gives cur back the next original, and tail.next = clone with tail = clone adds the copy. It steps with plain cur = cur.next, which already skips the copy, and at the end dummy.next is the first copy.

main prints the copy as [[7,null], [13,0], [11,4], [10,2], [1,0]]: the second node's random is the node at position 0 of its own list, and so on. The original prints the same, so the third pass restored it. The reference check prints true, since neither the copy's head nor the random of 13' is an original node. The self-pointing node prints [[5,0]], and copying null prints null.

7How much it costs, and the mistakes to avoid

Let us count on the example first. Each of the three passes visited the 5 originals, 15 visits in all with a few assignments each. For n nodes that is about 3n, so the time is O(n), and since every node must be copied, no solution does better.

The n new nodes are the answer itself, so we do not count them as extra. Beyond them we keep cur, clone, dummy and tail, so the extra space is O(1), against O(n) for the HashMap and for the position lists.

Comparing the ways to copy the list
ApproachTimeExtra spaceInput changed?
Position lists and indexOfO(n^2)O(n)no
HashMap from original to copyO(n)O(n)no
Weave, set randoms, splitO(n)O(1)for a while, then restored

The edge cases need no special code. An empty list skips all three loops and returns null. A null random stays null in the copy, because the second pass skips it. A single node 5 pointing to itself gets 5'.random = 5.next = 5', as main shows. Repeated values cause no trouble, since we never look anything up by value.

Four mistakes are worth watching for. Setting randoms while weaving leaves some copies pointing at null. Forgetting the null check on X.random throws a NullPointerException. Skipping the third pass corrupts the caller's list. And setting a copy's random to X.random instead of X.random.next gives a shallow copy that still prints correctly.

8Follow-up questions

Could recursion with a map replace the passes?

Yes. A method copy(X) first returns null for null and returns map.get(X) if X has already been copied. Otherwise it makes the copy, puts it in the map straight away, and only then sets copy.next = copy(X.next) and copy.random = copy(X.random). Storing the copy before the recursive calls stops it going round forever when randoms point backwards. It is elegant, but it calls itself once per node along the next chain, so 100,000 nodes can overflow the call stack.

How does this relate to cloning a graph?

It is the same problem in its general form. In a graph a node can be reached by many edges, so, just as here, each original must get exactly one copy and we need a quick way from an original to its copy. For a graph we walk with breadth-first or depth-first search and keep a HashMap from original to copy, making a copy the first time we meet a node and connecting copies through the map. The weaving trick does not carry over, because it depends on every list node having one natural slot right behind it.

Is it safe to change the input list while copying?

Only when nobody else is reading the list during the copy. Between the first and third passes the original list has copies woven through it, so another thread walking it at that moment would see extra nodes. In a single-threaded interview setting the weaving method is fine, because the third pass restores every next reference before we return. If the list is shared, the HashMap version is the safer choice, since it never touches the input at all.

9Conclusion

We made a deep copy of a list whose nodes have next and random references. Because a random reference may point to a node not copied yet, we made every copy first and connected them second, which needs a quick way from an original to its copy. The woven list keeps each copy right behind its original, so X.random.next is the copy we need, and splitting the lists afterwards gives O(n) time and O(1) extra space. The clue to remember is a copy whose references can point anywhere: make first, connect second, and keep a one-step way from each original to its copy.

What to say in the interviewAbout 90 seconds aloud

Open with

The difficulty is the random pointer. In one walk, a random may point to a node I have not copied yet, and even when the copy exists I cannot reach it from the original.

Then, if they want more

So I make all the copies first and connect them second, with a quick way from an original to its copy. Keeping two lists and finding each random target with indexOf is O(n squared).

A HashMap from original to copy fixes that: one pass makes every copy, a second sets copy next to map get of next and copy random to map get of random, and get of null is null. That is O(n) time and O(n) extra space.

To avoid the map, I weave each copy right behind its original, so the copy of X is X dot next. Then for each original with a non-null random I set X dot next dot random to X dot random dot next, the copy of the node X points to.

Finally I split the lists: each original gets its old next back and the copies are chained behind a dummy head. That is O(n) time and O(1) extra space besides the new nodes, and the input ends up unchanged. A null head returns null, and a node whose random is itself works with the same line.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 45 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Make a deep copy of a linked list where each node also has a random pointer.": https://scrivio-interview-library.netlify.app/data-structures/solutions/make-a-deep-copy-of-a-linked-list-where-each-node-also-has-a-ran-bd559f/