Depth-First Search
Medium

Clone Graph

Deep copy a connected undirected graph.
Examples
Input:adjList = [[2,4],[1,3],[2,4],[1,3]]
Output:[[2,4],[1,3],[2,4],[1,3]]
Explain:

Return a deep copy of the graph.

Problem Understanding

Given a reference of a node in a connected undirected graph.
Return a deep copy (clone).

Deep Copy: New nodes, new edges. You cannot return references to the original nodes.

Algorithm Strategy

We need to traverse the entire graph and create a copy of each node exactly once.

Key Tool: HashMap<OldNode, NewNode>.

  1. Check Map: If we already cloned this node, return the NewNode from the map (handles cycles).
  2. Create: If not, create NewNode(val) and add to map.
  3. Recurse: Iterate through OldNode.neighbors. For each neighbor, recursively call clone(neighbor) and add the result to NewNode.neighbors.
Visualization
Step 1 / 18
11 (Old)22 (Old)33 (Old)
Adjacency List(Map<Node, List>)

Start Clone Graph. We need to create a deep copy of each node.

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep