PracticeNeetCode ↗LeetCode ↗
Each node in this linked list carries an extra random pointer that can point to any node in the list, or to None. Return a deep copy of the list — a fully independent structure with the same values and the same relative next/random wiring.
random pointers even before the whole list is built.next and random using the map.None → None up front avoids special-casing random pointers that point to nothing.old_node → copy in a hashmap.copy.next = mapping[node.next] and copy.random = mapping[node.random].mapping[head] as the head of the copied list.Time: O(n) — Space: O(n)
class Node:
def __init__(self, x: int, next=None, random=None):
self.val = x
self.next = next
self.random = random
def copyRandomList(head: "Node | None") -> "Node | None":
if not head:
return None
mapping = {None: None}
curr = head
while curr:
mapping[curr] = Node(curr.val)
curr = curr.next
curr = head
while curr:
mapping[curr].next = mapping[curr.next]
mapping[curr].random = mapping[curr.random]
curr = curr.next
return mapping[head]How the solution above works, piece by piece.
mapping = {None: None}: old node → new node. The None entry means a missing next or random maps to None automatically.mapping[curr].next = mapping[curr.next] and mapping[curr].random = mapping[curr.random].random pointer can point forward to a node whose copy wouldn't exist yet in a single pass.mapping[head]. O(n) time, O(n) space for the map.Running it on the example (random targets: 7 → None, 13 → 7, 11 → 1, 10 → 11, 1 → 7):
original → copy in mapping (dotted lines). Pass 2 uses that map to point each copy's next and random at the matching copies, never at original nodes.