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.
- 0 <= n <= 1000
- -10⁴ <= Node.val <= 10⁴
- Node.random is null or is pointing to some node in the linked list.
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
xis simplyx.next. - Wiring random: so the copy of
x.randomisx.random.next.
When every random is set, one more pass pulls the two lists apart.
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.
Approach
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.
Two ways to solve it
Put each copy right after its original, set randoms through x.random.next, then split.
- Memory: no map at all.
- Watch out: the last pass must restore the original list.
First pass makes every copy and stores it in a map; second pass sets next and random through the map.
- Simple: the original is never touched.
- Cost: one map entry per node.
Both run in O(n). Weaving wins on memory, which is the usual follow-up question; the map is the easier first answer. The steps, code and live demo follow weaving, and the map code comes after the demo.
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.
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.
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.
Code in Python, C++ and Java
.next of null would crash, which is why the code checks first..next of null would crash, which is why the code checks first..next of null would crash, which is why the code checks first.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.
Common pitfalls
Setting random while the copies are still being made
while cur:
cur.next = Node(cur.val, cur.next)
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next# 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
cur.next.random = cur.random.next
if cur.random:
cur.next.random = cur.random.nextrandom 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
return head.next
while cur:
copy = cur.next
cur.next = copy.next
copy.next = copy.next.next if copy.next else None
cur = cur.next
return copy_headThe 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.
Edge cases
head is null, so return null before any pass runs. Without the check, head.next in the last pass would fail.
[[1,0]]cur.random.next is that node's own copy, so the copy points to itself too. No special case is needed.
Complexity
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.