Clone Graph
The problem
Section titled “The problem”Each node has a value and a list of neighbor nodes. You get one node of a connected undirected graph. Return a deep copy: brand new nodes with the same values and the same connections. No node in the copy may be one from the original.
1 -- 2| | -> a copy of node 1, with its own copies of 2, 3 and 44 -- 3 wired up the same wayKey insight
Section titled “Key insight”Copying a node is easy. The hard part is cycles and shared neighbors: node 3 can be reached from both 2 and 4, and you must create one copy of it, not two.
Keep a hash map from old node to its clone. Before creating a clone, check the map. If a clone exists, reuse it; if not, create it and recurse into that node’s neighbors. The map also acts as the visited set, so cycles can’t cause infinite recursion. Create the clone and put it in the map before recursing into its neighbors.
Show solutionHide solution
def clone_graph(node: Optional[Node]) -> Optional[Node]: if node is None: return None clones = {node: Node(node.val)} # old node -> its clone (doubles as visited set)
def dfs(old: Node) -> None: for nb in old.neighbors: if nb not in clones: clones[nb] = Node(nb.val) dfs(nb) clones[old].neighbors.append(clones[nb])
dfs(node) return clones[node]export function cloneGraph(node: Node | null): Node | null { if (node === null) return null; const clones = new Map<Node, Node>([[node, new Node(node.val)]]); // old -> clone (also the visited set)
function dfs(old: Node): void { for (const nb of old.neighbors) { if (!clones.has(nb)) { clones.set(nb, new Node(nb.val)); dfs(nb); } clones.get(old)!.neighbors.push(clones.get(nb)!); } }
dfs(node); return clones.get(node)!;}class Solution { private final Map<Node, Node> clones = new HashMap<>(); // old node -> its clone (also the visited set)
public Node cloneGraph(Node node) { if (node == null) return null; clones.clear(); clones.put(node, new Node(node.val)); dfs(node); return clones.get(node); }
private void dfs(Node old) { for (Node nb : old.neighbors) { if (!clones.containsKey(nb)) { clones.put(nb, new Node(nb.val)); dfs(nb); } clones.get(old).neighbors.add(clones.get(nb)); } }}Complexity
Section titled “Complexity”- Time: O(V + E) — each node is cloned once and each edge is walked once per endpoint.
- Space: O(V) — the map holds one entry per node, plus recursion depth up to V.
Watch out for
Section titled “Watch out for”- Register the clone before recursing. If you add it to the map afterwards, a cycle recurses forever.
- Empty input. The node can be
null; returnnull. - Don’t copy neighbor lists by reference.
new_node.neighbors = old.neighborsis a shallow copy and silently shares the original nodes. - Deep recursion. Graphs here are small (up to 100 nodes). For bigger ones, use BFS with a queue; the map logic is identical.
Variations
Section titled “Variations”Copy List with Random Pointer (LeetCode 138)
Section titled “Copy List with Random Pointer (LeetCode 138)”Each list node also has a random pointer to any node. The trick: the same old-to-new
map. First pass creates every clone; second pass sets next and random by looking up
the map.
Find if Path Exists in Graph (LeetCode 1971)
Section titled “Find if Path Exists in Graph (LeetCode 1971)”Given edges as pairs, is there a path from source to destination? The trick:
build an adjacency list from the pairs, then DFS or BFS from source with a visited set.