Copy List with Random Pointer (LeetCode 138): Solution and Explanation

Medium
Hash Table
Linked List

Each node in a linked list has a next pointer and a random pointer that can point to any node in the list or to null. Build a deep copy, a brand new list whose nodes mirror the original's values and pointer structure without referencing any original node.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Copying next pointers is easy: walk the list and create nodes as you go. The difficulty is the random pointer. When you copy node A, its random target might be a node you have not created yet, and even if you have, you need a way to find the copy that corresponds to a given original node.

The standard first solution uses a hash map from each original node to its copy. One pass creates all copies, and a second pass sets copy.next = map[orig.next] and copy.random = map[orig.random]. That is O(n) time and clean, but it spends O(n) extra memory on the map.

The interleaving trick gets rid of the map by storing the mapping inside the list itself. Insert each copy directly after its original, so the list becomes A, A', B, B', C, C'. Now the copy of any original node X is simply X.next. That means the copy of X.random is X.random.next, which lets you set every random pointer in one pass with no lookup table.

The last step untangles the two lists. Walk the interleaved list, point each original back at the next original and each copy at the next copy. The original list is restored exactly as it was, and the copies form an independent list whose head you return.

Approach: Interleave, assign randoms, separate

  1. If head is None, return None.
  2. First pass: for each original node curr, create copy = Node(curr.val, curr.next), set curr.next = copy, and move to copy.next, so each copy sits right after its original.
  3. Second pass: for each original curr, if curr.random exists, set curr.next.random = curr.random.next, then jump two nodes ahead.
  4. Third pass: use a dummy node and copy_curr pointer. For each original, link copy_curr.next = curr.next, restore curr.next = curr.next.next, and advance both pointers.
  5. Return dummy.next, the head of the copied list.

Step-by-step example

A(1) -> B(2) -> C(3), with A.random = C, B.random = A, C.random = null
  1. After the first pass the list is A -> A' -> B -> B' -> C -> C', where each primed node holds the same value as its original.
  2. Second pass at A: A.random is C, so A'.random = C.next, which is C'.
  3. At B: B.random is A, so B'.random = A.next, which is A'. At C: C.random is null, so C'.random stays null.
  4. Third pass: link dummy to A' and restore A.next to B, then link A' to B' and restore B.next to C, then link B' to C' and restore C.next to null.
  5. The original list is back to A -> B -> C, and the returned copy is A'(1) -> B'(2) -> C'(3) with A'.random = C' and B'.random = A'.

Code: Python, Java, C++

1class Solution:
2    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
3        if not head:
4            return None
5
6        # Step 1: Create interleaved list
7        curr = head
8        while curr:
9            copy = Node(curr.val, curr.next)
10            curr.next = copy
11            curr = copy.next
12
13        # Step 2: Set random pointers
14        curr = head
15        while curr:
16            if curr.random:
17                curr.next.random = curr.random.next
18            curr = curr.next.next
19
20        # Step 3: Separate lists
21        dummy = Node(0)
22        copy_curr = dummy
23        curr = head
24        while curr:
25            copy_curr.next = curr.next
26            curr.next = curr.next.next
27            copy_curr = copy_curr.next
28            curr = curr.next
29
30        return dummy.next

Time and space complexity

Time

O(n)

Each of the three passes walks the list once, and every step does constant work.

Space

O(1)

Apart from the n new nodes that make up the required output, only a few pointers are used. No hash map is needed.

Other approaches

Hash map from original to copy (time O(n), space O(n))

Create a copy of every node in one pass and record it in a map, then set each copy's next and random by looking up the originals' targets. It is the easiest version to explain and does not modify the input list even temporarily.

Recursive copy with memoization (time O(n), space O(n))

A recursive function returns the copy of a node, creating it on first visit and caching it in a map, then recursively copies next and random. It is short but can hit recursion limits on long lists.

Common mistakes

  • Setting curr.next.random = curr.random instead of curr.random.next, which makes the copy point back into the original list.
  • Skipping the null check on curr.random, which crashes when a node has no random target.
  • Assigning random pointers in the same pass that separates the lists. Once the interleaving is broken, X.random.next no longer leads to the copy.
  • Forgetting to restore the original list's next pointers, which leaves the input modified and can fail the judge's checks.

Frequently asked questions

How do you copy a list with random pointers in O(1) space?

Interleave each copy right after its original, so the copy of any node X is X.next. Then set each copy's random pointer to X.random.next, and finally split the interleaved list into the original and the copy.

Is the hash map solution acceptable?

Yes. It runs in O(n) time and is often the first answer interviewers expect. The interleaving approach is the follow-up when they ask you to avoid the extra memory.

What does deep copy mean here?

Every node in the result must be newly created, and none of the copied next or random pointers may refer to nodes from the original list. The structure must match exactly.

Does the interleaving approach modify the original list?

Only temporarily. The final pass restores every original next pointer, so the input list ends up exactly as it started.