← Visualizers
Traversal · 1.H · Deep Copying Graphs LeetCode 133

Clone Graph / visualized

Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list of its neighbors.

Original vs. Cloned Graph View

idle
INVARIANT Memoized Cloning Invariant: Undirected cycles cause infinite cloning loops unless visited nodes are memoized upfront. Maintain Map<Node, Node>. Instantiate clone copy, store map.put(u, copy) immediately, then recurse into neighbors. Time is O(V + E), Space is O(V).
Original Graph (addr: 0x100+)
Deep Copy Graph (addr: 0x200+)
HashMap (Original → Clone): {}
Press Run to begin.
0 / 0

Java 21 Solution (DFS)

INTERVIEW SCRIPT

How to Explain Clone Graph to an Interviewer

1. The Infinite Recursion Hazard

"Because edges are bidirectional, cloning node A's neighbor B will immediately attempt to clone B's neighbor A, creating an infinite ping-pong loop without a visited map."

2. Register in Map Immediately

"Instantiate Node copy = new Node(node.val) and store it in map.put(node, copy) BEFORE making any recursive neighbor calls. This breaks cycles instantly."

3. DFS Function Contract

"The helper clone(node, map) returns the cloned reference. If map.containsKey(node), return map.get(node). Otherwise clone, memoize, iterate neighbors, and return."

4. Complexity Mastery

"Every node and edge is visited and duplicated exactly once. Time complexity is $O(V + E)$ and auxiliary space is $O(V)$ for the HashMap and recursion stack depth."

O(V + E) time · O(V) space · Memoized graph cloning · Dual granularity navigation