Clone Graph (LeetCode 133): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Create an empty dictionary
oldToNewmapping original nodes to their clones. - Define
dfs(node). Ifnodeis already inoldToNew, return its existing clone. - Otherwise create
copy = Node(node.val)and store it inoldToNew[node]before looking at any neighbors. - For each neighbor of the original node, call
dfs(nei)and append the returned clone tocopy.neighbors. - Return
copy. The entry point returnsdfs(node), or None if the input node is None.
Step-by-step example
adjList = [[2,4],[1,3],[2,4],[1,3]]
- 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. - 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. - 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. - Clone 4's neighbors 1 and 3 are both in the map, so it links to clone 1 and clone 3 and returns.
- 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].
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 None1class Solution {
2 public Node cloneGraph(Node node) {
3 if (node == null) return null;
4 HashMap<Node, Node> oldToNew = new HashMap<>();
5 return dfs(node, oldToNew);
6 }
7
8 public Node dfs(Node node, HashMap<Node, Node> map) {
9 if (map.containsKey(node)) return map.get(node);
10
11 Node copy = new Node(node.val);
12 map.put(node, copy);
13
14 for (Node nei : node.neighbors) {
15 copy.neighbors.add(dfs(nei, map));
16 }
17
18 return copy;
19 }
20}1class Solution {
2 unordered_map<Node*, Node*> oldToNew;
3public:
4 Node* cloneGraph(Node* node) {
5 if (!node) return nullptr;
6 if (oldToNew.count(node)) return oldToNew[node];
7
8 Node* copy = new Node(node->val);
9 oldToNew[node] = copy;
10
11 for (auto nei : node->neighbors) {
12 copy->neighbors.push_back(cloneGraph(nei));
13 }
14
15 return copy;
16 }
17};Time and space complexity
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.
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.neighborsinstead 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
nodeis None, return None rather than callingnode.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.