Clone Graph (LeetCode 133): Solution and Explanation

Medium
Hash Table
Depth First Search
Breadth First Search
Graph

You are given a reference to one node of a connected, undirected graph, where each node stores a value and a list of neighbors. Return a deep copy of the whole graph: new node objects with the same values and the same neighbor structure, sharing nothing with the original.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Copying a tree is easy with recursion: copy the node, then copy each child. A graph breaks that idea in two ways. Nodes can be reached along several paths, so a naive copy would create duplicates of the same node, and undirected edges form cycles, so naive recursion would bounce between two neighbors forever.

Both problems have the same fix: remember what you have already copied. Keep a hash map from each original node to its clone. Before copying a node, check the map. If a clone already exists, return it instead of making another. This guarantees exactly one clone per original node, and it also stops cycles, because returning to a node you have seen ends that branch of the recursion.

The order of operations matters. You must put the new clone into the map before recursing into its neighbors. When the DFS walks around a cycle and comes back to the node it started from, the lookup succeeds and returns the clone that is still being built. Its neighbor list fills in as the recursion unwinds, and by the time the top call returns, every clone has its complete set of neighbor references.

Approach: DFS with an original-to-clone hash map

  1. Create an empty dictionary oldToNew mapping original nodes to their clones.
  2. Define dfs(node). If node is already in oldToNew, return its existing clone.
  3. Otherwise create copy = Node(node.val) and store it in oldToNew[node] before looking at any neighbors.
  4. For each neighbor of the original node, call dfs(nei) and append the returned clone to copy.neighbors.
  5. Return copy. The entry point returns dfs(node), or None if the input node is None.

Step-by-step example

adjList = [[2,4],[1,3],[2,4],[1,3]]
  1. The graph is a square: 1 connects to 2 and 4, and 3 connects to 2 and 4. dfs(1) creates clone 1 and records it.
  2. Clone 1 looks at neighbor 2, so dfs(2) creates clone 2. Its first neighbor is 1, which is already in the map, so clone 2 gets clone 1 as a neighbor.
  3. Clone 2 then visits 3, creating clone 3. Its neighbor 2 is in the map, and its neighbor 4 is new, so dfs(4) creates clone 4.
  4. Clone 4's neighbors 1 and 3 are both in the map, so it links to clone 1 and clone 3 and returns.
  5. The recursion unwinds: clone 3 gets [2, 4], clone 2 gets [1, 3], and back at node 1 the neighbor 4 is found in the map, so clone 1 gets [2, 4].
  6. dfs(1) returns clone 1, the entry point to a full independent copy of the square.

Code: Python, Java, C++

1class Solution:
2    def cloneGraph(self, node: 'Node') -> 'Node':
3        oldToNew = {}
4        
5        def dfs(node):
6            if node in oldToNew:
7                return oldToNew[node]
8            
9            copy = Node(node.val)
10            oldToNew[node] = copy
11            for nei in node.neighbors:
12                copy.neighbors.append(dfs(nei))
13            return copy
14            
15        return dfs(node) if node else None

Time and space complexity

Time

O(V + E)

Each node is cloned once, and each adjacency entry is followed once from each side of the edge, so the work is linear in the number of nodes plus edges.

Space

O(V)

The hash map stores one entry per node, and the recursion stack can reach V frames on a long path-shaped graph. The cloned graph itself is output, not extra space.

Other approaches

BFS with a queue (time O(V + E), space O(V))

Clone the start node, put the original in a queue, and for each popped node create clones of any unseen neighbors, enqueue those originals, and link the clones. It uses the same map and avoids deep recursion.

Array indexed by value (time O(V + E), space O(V))

Because node values here are unique and run from 1 to n, an array of size n plus 1 can replace the hash map. It is slightly faster but depends on that specific labeling.

Common mistakes

  • Adding the clone to the map after processing neighbors. On a cycle, the DFS returns to the node before it is recorded and recurses forever.
  • Appending original neighbors to copy.neighbors instead of their clones, which makes the copy point back into the old graph.
  • Keying the map by node value in a graph where values may repeat. Key by the node object itself to be safe.
  • Not handling an empty input. If node is None, return None rather than calling node.val.

Frequently asked questions

How do you handle cycles when cloning a graph?

Keep a map from original nodes to their clones and check it before creating a new node. When the traversal comes back to a node already in the map, it reuses that clone instead of recursing again.

DFS or BFS for Clone Graph?

Both work in O(V + E) time with the same hash map. DFS is shorter, while BFS avoids recursion depth limits on very long graphs.

What does a deep copy mean here?

Every node in the result must be a newly created object, and its neighbor list must refer only to other new objects. No reference in the copy may point to a node from the original graph.