Skip to content

Clone Graph

MediumLeetCode #133Time O(V + E)Space O(V)

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 4
4 -- 3 wired up the same way

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]
  • 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.
  • Register the clone before recursing. If you add it to the map afterwards, a cycle recurses forever.
  • Empty input. The node can be null; return null.
  • Don’t copy neighbor lists by reference. new_node.neighbors = old.neighbors is 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.

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.