Clone Graph
Medium · Graphs
Jump to codeDeep-copy the connected component reachable from a graph node. Each node has a value and a list of neighboring nodes; cycles may occur. Return null for a null input.
Examples
Example 1
node = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Example 2
node = [[]]
Output: [[]]
Constraints
- 0 <= The number of nodes in the graph <= 100.
- 1 <= Node.val <= 100
- There are no duplicate edges and no self-loops in the graph.
Function contract
The input is an adjacency list of a connected graph. Node values are 1-based row numbers. The grader constructs Node objects and verifies the returned graph is a deep copy with the same edges.
Need a hint?
Remember clones by original node identity before traversing edges.
Asked in real interviews
Candidates reported versions of Clone Graph from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Create a map from original nodes to copies. On first visit, allocate and store a copy, then populate its neighbors with recursively obtained copies. Storing before recursion breaks cycles. Equal values alone must not merge distinct nodes.
Complexity
O(V + E) time and O(V) auxiliary space, plus the copied graph.
Python reference solution
def cloneGraph(node):
if node is None:
return None
copies = {node: Node(node.val)}
queue = [node]
for original in queue:
for neighbor in original.neighbors:
if neighbor not in copies:
copies[neighbor] = Node(neighbor.val)
queue.append(neighbor)
copies[original].neighbors.append(copies[neighbor])
return copies[node]
JavaScript solution
function cloneGraph(node) {
if (!node) return null;
const copies = new Map([[node, new Node(node.val)]]), queue = [node];
for (let head = 0; head < queue.length; head++) {
const original = queue[head];
for (const neighbor of original.neighbors) {
if (!copies.has(neighbor)) {
copies.set(neighbor, new Node(neighbor.val));
queue.push(neighbor);
}
copies.get(original).neighbors.push(copies.get(neighbor));
}
}
return copies.get(node);
}
Java solution
import java.util.*;
class Solution {
public Node cloneGraph(Node node) {
if (node == null) return null;
Map<Node, Node> copies = new HashMap<>();
Queue<Node> queue = new ArrayDeque<>();
copies.put(node, new Node(node.val));
queue.add(node);
while (!queue.isEmpty()) {
Node original = queue.remove();
for (Node neighbor : original.neighbors) {
if (!copies.containsKey(neighbor)) {
copies.put(neighbor, new Node(neighbor.val));
queue.add(neighbor);
}
copies.get(original).neighbors.add(copies.get(neighbor));
}
}
return copies.get(node);
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
Node* cloneGraph(Node* node) {
if (!node) return nullptr;
unordered_map<Node*, Node*> copies{{node, new Node(node->val)}};
queue<Node*> pending;
pending.push(node);
while (!pending.empty()) {
Node* original = pending.front(); pending.pop();
for (Node* neighbor : original->neighbors) {
if (!copies.count(neighbor)) {
copies[neighbor] = new Node(neighbor->val);
pending.push(neighbor);
}
copies[original]->neighbors.push_back(copies[neighbor]);
}
}
return copies[node];
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
[
2,
4
],
[
1,
3
],
[
2,
4
],
[
1,
3
]
]
][
[
2,
4
],
[
1,
3
],
[
2,
4
],
[
1,
3
]
][
[
[]
]
][ [] ]
[ [] ]
[]
[
[
[
2
],
[
1
]
]
][
[
2
],
[
1
]
][
[
[
2
],
[
1,
3
],
[
2
]
]
][
[
2
],
[
1,
3
],
[
2
]
]Drafts are saved per language in this browser when storage is available.