Given a reference to a node in a connected, undirected graph, return a deep copy of the graph. Each node has an integer value and a list of neighbors. Node values are unique from 1 to n.
oldToNew map) — "intersection 3 on the original map corresponds to intersection 3* on the copy."The map lookup if nei not in oldToNew ensures each node is cloned exactly once. Even if three different paths lead to node 5, only the first creates the clone — subsequent visits just retrieve it from the map. This handles all cycles automatically.
| Approach | Time | Space | Notes |
|---|---|---|---|
| DFS (recursive) | O(V+E) | O(V) | Elegant; call stack up to V deep |
| BFS (queue) ✓ | O(V+E) | O(V) | Iterative; no stack overflow risk |
Left = original graph · Right = cloned graph being built
● Orange = active node · ● Amber = in queue or neighbor being checked · ● Green = cloned
DFS is more concise. The map is checked at the top of each call — if already cloned, return immediately. This handles cycles without any explicit visited tracking.
def cloneGraph(self, node):
oldToNew = {}
def dfs(node):
if node in oldToNew:
return oldToNew[node] # already cloned — reuse!
copy = Node(node.val)
oldToNew[node] = copy # store BEFORE recursing (handles cycles)
for nei in node.neighbors:
copy.neighbors.append(dfs(nei))
return copy
return dfs(node) if node else NoneWithout the map, DFS will recurse infinitely on any back-edge. Always store the clone in the map before recursing into neighbors — not after.
# WRONG: stores after recursion — infinite loop on cycles
copy = Node(node.val)
for nei in node.neighbors: # ← recurses before storing!
copy.neighbors.append(dfs(nei))
oldToNew[node] = copy # too late
# CORRECT: stores before recursion
copy = Node(node.val)
oldToNew[node] = copy # store first
for nei in node.neighbors:
copy.neighbors.append(dfs(nei))Two neighbors of different nodes may point to the same original node. Without the map, you'd create two separate clone objects — breaking the structure. The map guarantees a single clone per original node.
Discussion
…