15% off all plans & roadmaps Use code

See plans

Copy List with Random Pointer

Updated

TL;DR: Build a deep copy of a linked list where each node also has a random pointer. Map every original node to its copy, or weave copies into the list, so each random pointer lands on a new node.

Problem

A linked list of length n is given. Each node has a next pointer and an extra random pointer, which can point to any node in the list or to null.

Build a deep copy of the list. The copy must contain exactly n brand new nodes. Each new node has the same value as its original. The next and random pointers of the new nodes must point to new nodes, so the copied list has the same shape as the original. No pointer in the new list may point to a node of the original list.

For example, if original nodes X and Y satisfy X.random --> Y, then the corresponding copies x and y must satisfy x.random --> y.

Return the head of the copied list.

The list is shown in the input and output as n pairs [val, random_index]. Here val is Node.val, and random_index is the index (from 0 to n-1) of the node that random points to, or null if it points to nothing. Your code receives only the head of the original list.

Example 1

Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]

Example 2

Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]

Example 3

Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]

Example 4

Input: head = []
Output: []
Explanation: The list is empty (a null pointer), so return null.

Constraints

  • 0 <= n <= 1000
  • -10000 <= Node.val <= 10000
  • Node.random is null or points to some node in the list.

Constraints that matter

  • n is at most 1000, so an O(n^2) solution does about 10^6 steps and passes, but an interviewer expects O(n).
  • Random pointers can point forward, backward, or to the node itself, so you cannot finish a node's random pointer while walking left to right without extra bookkeeping.
  • n can be 0, so the head can be null. Every approach needs a null check up front.
  • Values can repeat and can be negative, so you cannot identify a node by its value. You must identify nodes by reference or by position.
  • A random pointer is never outside the list, so every non-null random target has a copy once all copies exist.

View on LeetCode

Hints

Hint 1

The next pointers are easy to copy because you walk the list in order.

Hint 2

Copy the list in one pass using only next pointers.

Solution

Intuition

The next pointers are easy to copy because you walk the list in order. The hard part is random. When you reach a node, its random target may be a node you have not copied yet, or one you copied long ago. You need to answer one question fast: given an original node, where is its copy?

It is like a row of pages where every original page is followed by its photocopy. To find the copy of any page, you look at the page right after it, so the row itself works as the index.

That question is a lookup from original node to copy, and a hash map answers it in O(1). This is the deep copy pattern from graph problems. The list is a graph where each node has up to two outgoing edges, next and random. Cloning a graph means creating each node once and then wiring edges through the lookup.

The lookup does not need a separate structure. You can place each copy directly after its original in the same list. Then the copy of any node X is always X.next, and the copy of X.random is X.random.next. The list itself becomes the map, and extra space drops to O(1).

In both versions the order of work is the same. Create all copies first, then wire pointers. If you wire while creating, you hit random targets that do not exist yet.

Watch the pattern animation

Worked example

Input: head = [[5,2],[6,0],[7,1],[8,3]]
Output: [[5,2],[6,0],[7,1],[8,3]]
Explanation: The list has four nodes with values 5, 6, 7, 8 at indices 0 to 3. Random pointers go 5 to 7, 6 to 5, 7 to 6, and 8 to itself. The copy has four new nodes with the same values, and every next and random pointer points inside the copy. Printed as index pairs, it matches the input.

Approach 1: Brute force: search for each random target

Copy the list in one pass using only next pointers. Then fix each random pointer by searching.

For each original node, you scan from the head to find the index of its random target. Then you walk the same number of steps in the copy to find the matching new node.

Steps

  1. Return null if head is null.
  2. Walk the original list and build a copy chain with the same values, linking only next.
  3. Walk the original and the copy together, one step at a time.
  4. For each original node whose random is not null, scan from head until you reach the random target, counting steps as idx.
  5. Walk idx steps from the head of the copy and set the copy's random to that node.
  6. Return the head of the copy chain.

Dry run

Example: values 5, 6, 7, 8 with randoms 5 to 7, 6 to 5, 7 to 6, 8 to 8.

Pass 1 builds the chain 5' -> 6' -> 7' -> 8' with no random pointers.

Pass 2, node 5: its random is node 7, found after 2 steps from the head, so idx = 2. Walking 2 steps in the copy reaches 7'. Set 5'.random = 7'.

Node 6: random is node 5, idx = 0, so 6'.random = 5'.

Node 7: random is node 6, idx = 1, so 7'.random = 6'.

Node 8: random is node 8, idx = 3, so 8'.random = 8'.

The copy reads [[5,2],[6,0],[7,1],[8,3]], which matches the output.

Complexity

TimeO(n^2)
SpaceO(1) extra, not counting the n new nodes

Let n be the number of nodes. Building the chain takes n steps. For each of the n nodes, the index search scans at most n nodes and the walk in the copy takes at most n more. The second pass therefore costs up to 2 * n * n steps, which is O(n^2). Besides the output nodes, you keep only a few pointers and an integer.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def copyRandomList(self, head: Optional[Node]) -> Optional[Node]:
        if not head:
            return None
        # Pass 1: copy the chain using next pointers only
        dummy = Node(0)
        tail = dummy
        cur = head
        while cur:
            tail.next = Node(cur.val)
            tail = tail.next
            cur = cur.next
        # Pass 2: find each random target by position
        o = head
        c = dummy.next
        while o:
            if o.random:
                idx = 0
                t = head
                while t is not o.random:
                    t = t.next
                    idx += 1
                target = dummy.next
                for _ in range(idx):
                    target = target.next
                c.random = target
            o = o.next
            c = c.next
        return dummy.next

Approach 2: Two-pass hash map

What's slow: for every node you re-scan the list to locate the copy of its random target. The same lookup is repeated n times at O(n) each.

The insight that fixes it: store each original node and its copy in a hash map. Build all copies in the first pass. In the second pass, every next and random target already has a copy, so wiring is one O(1) lookup per pointer.

Steps

  1. Create an empty map from original node to copy.
  2. Walk the list once. For each original node, create a new node with the same value and store it in the map.
  3. Walk the list a second time.
  4. For each original node cur, set map[cur].next = map[cur.next].
  5. Set map[cur].random = map[cur.random].
  6. Treat a null key as mapping to null so tail and null-random cases need no special branch.
  7. Return map[head], or null for an empty list.

Dry run

Example: values 5, 6, 7, 8 as nodes A, B, C, D. Randoms: A to C, B to A, C to B, D to D.

Pass 1 builds the map {A: A', B: B', C: C', D: D'} where each copy holds the same value and null pointers.

Pass 2, A: A'.next = B', A'.random = C'.

B: B'.next = C', B'.random = A'.

C: C'.next = D', C'.random = B'.

D: D'.next = null since D.next is null, and D'.random = D'.

Reading the copy from A' gives [[5,2],[6,0],[7,1],[8,3]], the expected output.

Complexity

TimeO(n)
SpaceO(n)

Let n be the number of nodes. Each of the two passes visits every node once and does a constant number of average O(1) hash operations, so time is O(n). The map holds one entry per node, which is n entries, so extra space is O(n) beyond the output nodes themselves.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def copyRandomList(self, head: Optional[Node]) -> Optional[Node]:
        # None maps to None so null pointers need no special case
        copies = {None: None}
        cur = head
        while cur:
            copies[cur] = Node(cur.val)
            cur = cur.next
        cur = head
        while cur:
            copies[cur].next = copies[cur.next]
            copies[cur].random = copies[cur.random]
            cur = cur.next
        return copies[head]
Deep Copy / Cloning pattern infographic for Copy List with Random Pointer

Solution pattern

Deep Copy / Cloning

Part of Graph Traversal Patterns (DFS & BFS)

Approach 3: Interleave copies in the listOptimalDeep Copy / Cloning

What's slow: nothing in time, but the hash map costs O(n) extra space to answer "where is the copy of X?".

The insight that fixes it: put each copy directly after its original, so the list reads A, A', B, B', and so on. The copy of any node X is X.next, and the copy of X.random is X.random.next. The list itself acts as the map. After wiring randoms, split the two lists apart and restore the original.

Why it is correct. Pass 1 puts every copy directly after its original, so X.next is always the copy of X. Pass 2 can therefore set each copy's random to cur.random.next, which is the correct copy of cur.random. Pass 3 restores the original next pointers and collects the copies in the same order, so the result matches the input structure exactly.

Steps

  1. Return null if head is null.
  2. Pass 1: for each original node, insert a new node with the same value right after it.
  3. Pass 2: for each original node cur, if cur.random is not null, set cur.next.random = cur.random.next. Then move two steps to the next original node.
  4. Pass 3: create a dummy head for the copy list.
  5. For each original node cur, let copy = cur.next. Set cur.next = copy.next to restore the original, and append copy to the copy list.
  6. Move cur to its restored next and repeat.
  7. Return the node after the dummy head.

Dry run

Example: nodes A5, B6, C7, D8 with randoms A to C, B to A, C to B, D to D.

After pass 1 the list is A -> A' -> B -> B' -> C -> C' -> D -> D'.

Pass 2 sets randoms through random.next.

A: random is C, so A'.random = C.next = C'.

B: random is A, so B'.random = A.next = A'.

C: random is B, so C'.random = B'.

D: random is D, so D'.random = D.next = D'.

Pass 3 splits the list. Starting at A, copy is A', set A.next = B and append A'. At B, append B' and set B.next = C.

At C, append C' and set C.next = D. At D, append D' and set D.next = null.

The copy list is 5' -> 6' -> 7' -> 8' with randoms to 7', 5', 6', 8'. That reads [[5,2],[6,0],[7,1],[8,3]]. The original list is intact.

Complexity

TimeO(n)
SpaceO(1) extra, not counting the n new nodes

Let n be the number of nodes. Each of the three passes touches each original node a constant number of times with O(1) pointer work, so time is O(n). The only memory beyond the output nodes is a few pointer variables, so extra space is O(1). The new nodes are required output, not extra space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def copyRandomList(self, head: Optional[Node]) -> Optional[Node]:
        if not head:
            return None
        # Pass 1: insert each copy right after its original
        cur = head
        while cur:
            nxt = cur.next
            cur.next = Node(cur.val)
            cur.next.next = nxt
            cur = nxt
        # Pass 2: the copy of cur.random is cur.random.next
        cur = head
        while cur:
            if cur.random:
                cur.next.random = cur.random.next
            cur = cur.next.next
        # Pass 3: split into the original list and the copy list
        dummy = Node(0)
        tail = dummy
        cur = head
        while cur:
            copy = cur.next
            cur.next = copy.next
            tail.next = copy
            tail = copy
            cur = cur.next
        return dummy.next

Common mistakes

  • Setting copy.random = original.random in any approach. That points the new list back into the old list. Look up the copy of the target instead, through the map or through random.next.
  • Wiring random pointers while creating nodes in a single left-to-right pass without a map. A forward random target does not exist yet. Create all copies first, or use a map that creates a copy on first sight.
  • Forgetting the null check on random in the interleaving version. cur.random.next throws on a null random. Guard with if cur.random.
  • Skipping pass 3 or leaving cur.next pointing at a copy. The original list must be restored, and the returned list must not contain original nodes. Set cur.next = copy.next before moving on.
  • Moving one step instead of two in pass 2 of the interleaving version. Using cur = cur.next lands on a copy, whose random is still unset or null. Use cur = cur.next.next.
  • Keying a map by node.val. Values repeat, as in [[3,null],[3,0],[3,null]], so copies overwrite each other. Key by the node reference itself.

Edge cases

  • Empty list (head = null): return null without touching any pointer.
  • Single node whose random points to itself: the copy's random must point to the copy, not the original.
  • All random pointers null: the result is a plain copy of the next chain.
  • Duplicate values such as [[3,null],[3,0],[3,null]]: nodes must be identified by reference, and the output must keep the random index 0 on the middle node.
  • Random pointers that point backward and forward in the same list: both must resolve to copies, which only works if all copies exist before wiring.
  • Maximum size n = 1000 with random pointers to the head: the O(n^2) approach still finishes, and the linear ones are far faster.

Follow-ups interviewers ask

Can you do it in O(1) extra space?
Yes. Interleave each copy after its original, set copy.random = original.random.next, then split the two lists and restore the original. This uses only a few pointers beyond the output nodes. The cost is that you temporarily modify the input, so it is not safe if other threads read the list.
What if the structure is a general graph instead of a list, as in Clone Graph?
Use the same idea with a traversal. Keep a map from original node to copy. Run DFS or BFS, and when you reach a node, create its copy and store it in the map before visiting its neighbors. For each edge, look up or create the neighbor's copy and attach it. The map stops infinite loops on cycles and guarantees one copy per node.
How would you write the recursive version, and what is its risk?
Recurse on copy(node): return null for null, return the stored copy if the node is in the map, otherwise create the copy, store it, then set next and random by recursive calls. Storing before recursing is required to survive cycles. The depth can reach n, so on a very long list you risk a stack overflow. With n up to 1000 this is safe in most languages, but the iterative version avoids the question.

Copy List with Random Pointer FAQ

What is the time complexity of Copy List with Random Pointer?

The hash map and interleaving solutions run in O(n), where n is the number of nodes, because each node is visited a constant number of times. The brute force that searches for each random target takes O(n^2). The hash map version uses O(n) extra space and the interleaving version uses O(1).

Why use a hash map for Copy List with Random Pointer?

The hard part is finding the copy of a random target, which may sit anywhere in the list. A hash map from original node to copy answers that in O(1). Without it you rescan the list for each node, which costs O(n^2). Keying by node reference also handles duplicate values correctly.

Can Copy List with Random Pointer be solved in O(1) extra space?

Yes, by interleaving. You place each copy right after its original, set random pointers through random.next, and then separate the lists. It still creates n new nodes, since the output needs them, but it needs no map or recursion stack. It does modify the input temporarily, so you must restore it.

What is a deep copy in LeetCode 138?

A deep copy means every node in the result is a new object, and no pointer in it leads to an original node. Copying only the head, or reusing the original random targets, is a shallow copy and fails. The copied pointers must mirror the original structure exactly.

Is it better to build the map in one pass or two?

Two passes is easier to get right: create all copies, then wire. A one-pass version creates copies on demand while walking, using a helper that returns the existing copy or makes a new one. Both are O(n) time and O(n) space, so pick the one you can write without bugs.

Why does the Python solution use None as a map key?

Setting copies[None] = None lets copies[cur.next] and copies[cur.random] work when a pointer is null, with no if statement. Python dicts accept None as a key. Java's HashMap returns null for a missing key, Go returns nil, and C# dictionaries reject null keys, so C# needs an explicit null check.

Asked at

See which companies ask this — Pro

Practise it