Browse Curriculum
FAANGPrep Sprint
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 / 1

Visualization coming soon...

Initializing...

1x

Mapping Old Nodes to New Nodes to Avoid Cycles.

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.