Create an independent copy of every node and edge reachable from a given graph node.
Problem
Input. One GraphNode reference, or None, in a finite graph with integer values and ordered neighbor lists.
Output. Return the corresponding node in a newly allocated copy of the reachable component.
Rules. Preserve node values, neighbor order, repeated entries, shared targets, cycles, and self-loops.
Every copied edge must refer to copied nodes, never originals.
Equal values do not make two nodes identical. Leave the original graph unchanged.
Do not copy unreachable components; None returns None.
Example. A triangle of original nodes O1, O2, and O3 becomes a triangle of C1, C2, and C3.
Changing a copied node must not change its original.
Picture
Before processing O1, create C1 and record O1 -> C1.
When O1 discovers O2 and O3, allocate each copy once and enqueue each original once.
Back edges find existing copies; they do not restart copying.
The memo’s keys are object identities, not numeric labels.
Two different nodes labelled 7 still require two different copies.
Problem trace
Reuse the copy when a cycle returns; never link back to originals
Reference drawing
Problem trace
Reuse the copy when a cycle returns; never link back to originals
Execution trace
- edges
- [O1 <-> O2, O1 <-> O3, O2 <-> O3]
- edge labels
- false
- start
- O1
- edges
- [O1 <-> O2, O1 <-> O3, O2 <-> O3]→[O1 <-> O2, O1 <-> O3, O2 <-> O3, C1 -> C2]
- copies
- O1->C1→O1->C1, O2->C2
- node 4
- not shown→C2
- edges
- [O1 <-> O2, O1 <-> O3, O2 <-> O3, C1 -> C2]→[O1 <-> O2, O1 <-> O3, O2 <-> O3, C1 -> C2, C1 -> C3]
- copies
- O1->C1, O2->C2→O1->C1, O2->C2, O3->C3
- node 5
- not shown→C3
- edges
- [O1 <-> O2, O1 <-> O3, O2 <-> O3, C1 -> C2, C1 -> C3]→[O1 <-> O2, O1 <-> O3, O2 <-> O3, C1 -> C2, C1 -> C3, C2 -> C1, C2 -> C3]
- start
- O1→O2
- current
- O1→O2
- edges
- [O1 <-> O2, O1 <-> O3, O2 <-> O3, C1 -> C2, C1 -> C3, C2 -> C1, C2 -> C3]→[O1 <-> O2, O1 <-> O3, O2 <-> O3, C1 -> C2, C1 -> C3, C2 -> C1, C2 -> C3, C3 -> C1, C3 -> C2]
- start
- O2→O3
- current
- O2→O3
- current
- O3→return C1
- copies
- O1->C1, O2->C2, O3->C3→all clone edges stay inside C1,C2,C3
- result
- not shown→deep copy rooted at C1
- Recognize it
- A cyclic connected object must be deep-copied while preserving adjacency, so each original identity needs exactly one reusable copied identity before edges are wired.
- Keep true
- Every key in copies maps to exactly one clone, and after an original node is processed, its clone has one copied neighbor entry for every original neighbor processed in order.
- Reuse it
- When copying any cyclic object graph, allocate and memoize an object before traversing its references, then resolve every copied reference through that memo.
Invariant: every discovered original already has exactly one allocated copy, although its outgoing adjacency may still be incomplete. For each adjacency entry, append the mapped neighbor even when that neighbor was discovered earlier.
Code
This reference supplies identity-hashable GraphNode objects.
It does not define value-based equality, so equal labels do not merge dictionary keys.
from __future__ import annotations
from collections import deque
class GraphNode:
def __init__(self, val: int = 0, neighbors: list[GraphNode] | None = None) -> None:
self.val = val
self.neighbors = neighbors or []
def clone_graph(node: GraphNode | None) -> GraphNode | None:
if node is None:
return None
copies = {node: GraphNode(node.val)}
queue = deque([node])
while queue:
current = queue.popleft()
for neighbor in current.neighbors:
if neighbor not in copies:
copies[neighbor] = GraphNode(neighbor.val)
queue.append(neighbor)
copies[current].neighbors.append(copies[neighbor])
return copies[node]
For reachable nodes and adjacency entries, time is . Memo and queue use auxiliary space. Copied nodes and adjacency separately occupy output space. Repeated neighbor entries count separately in . Original nodes and lists remain unchanged.
Failure Check
Memoizing after following edges can recurse forever on a cycle.
A visited Boolean alone cannot identify the copied target.
Skipping edges to visited nodes drops back edges, shared references, and repeated entries.
Keying by val incorrectly merges distinct equal-valued originals.
Change the Traversal
New task: Use recursive DFS while preserving the same copying contract.
Picture and change: Keep allocation before descent.
Every recursive revisit returns the already allocated copy.
Use the supplied GraphNode above.
def clone_graph_dfs(node):
copies = {}
def visit(original):
if original is None:
return None
if original not in copies:
copies[original] = GraphNode(original.val)
copies[original].neighbors = [visit(neighbor) for neighbor in original.neighbors]
return copies[original]
return visit(node)
Check: Give two distinct 7 nodes a back edge and two repeated references to the second node.
Their copies remain distinct, repeated references share one target, and the back edge closes inside the copy.
Time and output bounds remain unchanged; recursive depth can reach and exceed Python’s limit.
Use when: DFS presentation is useful and recursive depth is acceptable.
Change the Root Boundary
New task: Copy several roots, including disconnected or overlapping components.
Picture and change: Seed one shared memo and queue.
Pass a sequence, since roots is read twice.
def clone_roots(roots):
copies, queue = {}, deque()
for root in roots:
if root is not None and root not in copies:
copies[root] = GraphNode(root.val)
queue.append(root)
while queue:
original = queue.popleft()
for neighbor in original.neighbors:
if neighbor not in copies:
copies[neighbor] = GraphNode(neighbor.val)
queue.append(neighbor)
copies[original].neighbors.append(copies[neighbor])
return [None if root is None else copies[root] for root in roots]
Check: [first, second, first, None] returns the same copied first twice, an independent copied second, and None.
Shared reachable nodes are copied once across roots.
For roots, time is and output space is ; memo/queue remain .
Keep the reference’s deque import.
Use when: Multiple entry points define the requested ownership boundary.
Transfer Check
Why is the memo more than a visited set?
Answer
It identifies the unique copied target needed for every reconstructed reference. Discovery alone prevents repeated work but cannot rebuild the edges. Compare tree copying when cycles and shared nodes are excluded by contract.