LeetCode #138 Medium

Copy List with Random Pointer

Copy List with Random Pointer is LeetCode 138 (Medium). Each node of a linked list has a next pointer and a random pointer, and random can point to any node in the list or be null. Return a deep copy: a list of brand-new nodes with the same values, where every next and random of a new node points to another new node, never back into the original.

  • The list has up to 1,000 nodes.
  • The judge also checks that the original list is unchanged after your function returns.
Constraints
  • 0 <= n <= 1000
  • -10⁴ <= Node.val <= 10⁴
  • Node.random is null or is pointing to some node in the linked list.
linked-listhash-table
Open on LeetCode ↗
02

Intuition

Copying next is easy: walk the list and make one new node per old node. The trouble is random. When you copy a node, its random may point to a node you have not copied yet, so there is nothing to point at.

The usual fix is a map from each old node to its copy. The O(1)-space trick keeps that map inside the list itself: put each copy directly after its original, so the list reads A → A' → B → B'.

  • Finding a copy: the copy of any old node x is simply x.next.
  • Wiring random: so the copy of x.random is x.random.next.

When every random is set, one more pass pulls the two lists apart.

How to spot this pattern

You need an "old node → new node" lookup, and the structure you are copying has room to hold it. Putting each copy next to its original turns the list itself into the lookup table.

03

Approach

Try it first

Before reading on, decide where you could put each new node so that, from any old node, you can reach its copy in one step without a hash map. Aim for O(n) time and O(1) extra space.

1

Weave a copy after every node

Walk the list. For each node cur, create a node with the same value and splice it between cur and cur.next. When the pass ends, every old node is followed by its own copy, which is the only lookup the next pass needs.

2

Point each copy's random at the right copy

Walk the old nodes, two steps at a time. If cur.random is set, point cur.next.random at cur.random.next. That node is the copy of cur.random, because every old node's next node is now its copy.

3

Pull the two lists apart

Walk once more. Point cur.next at the copy's next node, which is the next old node, and point the copy at that node's copy. This rebuilds the original exactly and links the copies into their own list, which starts at head.next.

04

Code in Python, C++ and Java

▶1from typing import Optional
▶2 
▶3 
▶4class Solution:
▶5 def copyRandomList(self, head: "Optional[Node]") -> "Optional[Node]":
▶6 if not head:
▶7 return None
▶8 
▶9 cur = head
▶10 while cur:
▶11 cur.next = Node(cur.val, cur.next)
▶12 cur = cur.next.next
▶13 
▶14 cur = head
▶15 while cur:
▶16 if cur.random:
▶17 cur.next.random = cur.random.next
▶18 cur = cur.next.next
▶19 
▶20 copy_head = head.next
▶21 cur = head
▶22 while cur:
▶23 copy = cur.next
▶24 cur.next = copy.next
▶25 copy.next = copy.next.next if copy.next else None
▶26 cur = cur.next
▶27 return copy_head
nextrandom713111015 old nodes, no copies yet
nodes5
copies0
The dashed arrows are the random pointers. A copy cannot point at the copy of its random target until that copy exists, so the copies are made first, each in the slot right below its original.
nextrandom77′1311101make 7′ and put it right after 7
cur7
copies1
The new node takes 7's place in the chain: 7 now points to its copy, and the copy points to 13. So the copy of 7 is always 7.next, and no map is needed.
nextrandom77′1313′11101make 13′ and put it right after 13
cur13
copies2
The new node takes 13's place in the chain: 13 now points to its copy, and the copy points to 11. So the copy of 13 is always 13.next, and no map is needed.
nextrandom77′1313′1111′101make 11′ and put it right after 11
cur11
copies3
The new node takes 11's place in the chain: 11 now points to its copy, and the copy points to 10. So the copy of 11 is always 11.next, and no map is needed.
nextrandom77′1313′1111′1010′1make 10′ and put it right after 10
cur10
copies4
The new node takes 10's place in the chain: 10 now points to its copy, and the copy points to 1. So the copy of 10 is always 10.next, and no map is needed.
nextrandom77′1313′1111′1010′11′make 1′ and put it right after 1
cur1
copies5
The new node takes 1's place in the chain: 1 now points to its copy, and the copy points to null. So the copy of 1 is always 1.next, and no map is needed.
nextrandom77′1313′1111′1010′11′7 has no random → its copy's stays empty
cur7
cur.randomnull
7's random is null, and a new node's random already starts as null, so there is nothing to set. Reading .next of null would crash, which is why the code checks first.
nextrandom77′1313′1111′1010′11′13 → 7, so its copy → 7′
cur.random7
copy.random7′7.next
13's random points to 7. The node right after 7 is 7′, so that is where the copy's random goes.
nextrandom77′1313′1111′1010′11′11 → 1, so its copy → 1′
cur.random1
copy.random1′1.next
11's random points to 1. The node right after 1 is 1′, so that is where the copy's random goes, even though it sits further along the list: it was made in the first pass.
nextrandom77′1313′1111′1010′11′10 → 11, so its copy → 11′
cur.random11
copy.random11′11.next
10's random points to 11. The node right after 11 is 11′, so that is where the copy's random goes.
nextrandom77′1313′1111′1010′11′1 → 7, so its copy → 7′
cur.random7
copy.random7′7.next
1's random points to 7. The node right after 7 is 7′, so that is where the copy's random goes.
nextrandom77′1313′1111′1010′11′unhook 7′ → 7 points to 13 again
7.next13
copy.next13′
7 skips over its copy and points to 13, which is how it was at the start. Its copy points to the copy of 13, the node right after 13.
nextrandom77′1313′1111′1010′11′unhook 13′ → 13 points to 11 again
13.next11
copy.next11′
13 skips over its copy and points to 11, which is how it was at the start. Its copy points to the copy of 11, the node right after 11.
nextrandom77′1313′1111′1010′11′unhook 11′ → 11 points to 10 again
11.next10
copy.next10′
11 skips over its copy and points to 10, which is how it was at the start. Its copy points to the copy of 10, the node right after 10.
nextrandom77′1313′1111′1010′11′unhook 10′ → 10 points to 1 again
10.next1
copy.next1′
10 skips over its copy and points to 1, which is how it was at the start. Its copy points to the copy of 1, the node right after 1.
nextrandom77′1313′1111′1010′11′unhook 1′ → 1 is the last node again
1.nextnull
copy.nextnull
1 skips over its copy and points to null, which is how it was at the start. Its copy points to null.
nextrandom77′1313′1111′1010′11′return the copy list, old list unchanged
copy head7′
extra memorya few pointers
Both rows now have the same shape: same values, same next order, same random targets. The bottom row is made only of new nodes, and the top row is exactly as it was given, which the judge also checks.
05

Hash map from old node to copy

The first loop creates a copy of every node and records it under its original. The second loop looks up the copy of each next and random target. Mapping None to None saves a null check for both pointers.

▶1from typing import Optional
▶2 
▶3 
▶4class Solution:
▶5 def copyRandomList(self, head: "Optional[Node]") -> "Optional[Node]":
▶6 copy_of = {None: None}
▶7 cur = head
▶8 while cur:
▶9 copy_of[cur] = Node(cur.val)
▶10 cur = cur.next
▶11 
▶12 cur = head
▶13 while cur:
▶14 copy_of[cur].next = copy_of[cur.next]
▶15 copy_of[cur].random = copy_of[cur.random]
▶16 cur = cur.next
▶17 return copy_of[head]
06

Common pitfalls

Setting random while the copies are still being made

✗ Wrong
while cur:
    cur.next = Node(cur.val, cur.next)
    if cur.random:
        cur.next.random = cur.random.next
    cur = cur.next.next
✓ Right
# pass 1: weave every copy
# pass 2: set every random
# pass 3: pull the lists apart

A random pointer can aim at a node further along that has no copy yet, so cur.random.next is still an old node. On [[1,1],[2,0]] the first copy's random lands on null instead of the copy of 2. Every copy has to exist before any random is set.

Reading .next of a null random

✗ Wrong
cur.next.random = cur.random.next
✓ Right
if cur.random:
    cur.next.random = cur.random.next

random is allowed to be null, and None.next raises an error on an input as small as [[1,null]]. A new node's random is already null, so skipping the line is the correct copy.

Returning the copy without restoring the original

✗ Wrong
return head.next
✓ Right
while cur:
    copy = cur.next
    cur.next = copy.next
    copy.next = copy.next.next if copy.next else None
    cur = cur.next
return copy_head

The copies may look right, but every old node still points at a new node. The judge compares the original list after your function returns and rejects the answer because an old node's next pointer was changed.

07

Edge cases

Empty list

head is null, so return null before any pass runs. Without the check, head.next in the last pass would fail.

A node whose random points to itself, as in [[1,0]]

cur.random.next is that node's own copy, so the copy points to itself too. No special case is needed.

08

Complexity

Time
O(n)
Space
O(1)
Three passes, each visiting every node once. Apart from the new nodes, which are the answer, only a few pointers are stored. The hash map version uses O(n) extra space for the map.
09

Copy List with Random Pointer FAQ

Can the copy be built with recursion?

Yes. A function copy(node) returns the stored copy if one exists; otherwise it creates one, stores it, and then sets next = copy(node.next) and random = copy(node.random). It still needs the map, and a 1,000-node chain means 1,000 nested calls, so it saves nothing over the loop version.