Copy List with Random Pointer
Difficulty: Medium · Pattern: Linked List · LeetCode #138
Each node has val, next and a random pointer to any node in the list (or null). Return a deep copy: brand-new nodes with the same structure; no pointer in the copy may reference the original list.
The tests describe a list as [[val, random_index], …] (null for no random pointer).
Examples
text
[[7,null],[13,0],[11,4],[10,2],[1,0]] → same structure, new nodes
[[1,1],[2,1]] → same structure, new nodesHints
- First create a copy of every node, then wire up next and random.
- A map from original node → copy makes the wiring easy.
- O(1)-space trick: interleave copies (A → A' → B → B' …), set the randoms, then separate the lists.
Approach
Hash map: pass 1 creates copy[node] = Node(node.val) for every node. Pass 2 sets copy[node].next = copy[node.next] and copy[node].random = copy[node.random] (null maps to null). Return copy[head]. O(n) time and space. The interleaving variant achieves O(1) extra space.
Complexity
Time: O(n). Space: O(n) (O(1) extra with interleaving).
Python solution
def copyRandomList(head):
if not head:
return None
copy = {}
cur = head
while cur:
copy[cur] = Node(cur.val)
cur = cur.next
cur = head
while cur:
copy[cur].next = copy.get(cur.next)
copy[cur].random = copy.get(cur.random)
cur = cur.next
return copy[head]JavaScript solution
function copyRandomList(head) {
if (!head) return null;
const copy = new Map();
for (let c = head; c; c = c.next) copy.set(c, new Node(c.val));
for (let c = head; c; c = c.next) { copy.get(c).next = copy.get(c.next) || null; copy.get(c).random = copy.get(c.random) || null; }
return copy.get(head);
}