Clone Graph
Pattern: BFS and DFS
Walk the graph with BFS (or DFS), keeping a map from each original node to its copy. The first time a node is met, create its copy; for every edge u-v, add v's copy to u's copy's neighbours. The map doubles as the visited set.
The problem
Given one node of a connected undirected graph, return a deep copy: new nodes with the same values and the same
connections. Each node has a value and a list of neighbours. The tests give the graph as LeetCode does (adj[i] lists
the neighbours of node i + 1), print the copy's adjacency, and check that it shares no node with the original.
Think first
- What must exist before you can link a copied edge?
- How do you avoid copying a node twice?
- Why is a plain visited set not enough?
Hints
Brute force, and why it fails
Copy nodes in one pass and edges in a second pass, using a list of all nodes: also O(V + E), but two walks.
The key insight
The original-to-copy map lets each edge be copied the moment it is seen, in one traversal.
Dry run
| copies | 1 |
|---|
adjList [[2, 4], [1, 3], [2, 4], [1, 3]]: four nodes in a square. Copy node 1.
The plan
copy = {start: new}; queue = [start]
while queue: u = pop
for v in u.neighbors: if v not in copy: copy[v] = new; push v
copy[u].neighbors.add(copy[v])
Complexity
- Time
O(V + E)- Space
O(V)
Each node and edge once.
Edge cases
- An empty graph: null.
- One node with no neighbours.
- Two nodes joined to each other.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public GNode cloneGraph(GNode node) {
if (node == null) return null;
Map<GNode, GNode> copy = new HashMap<>(); // original -> its copy, also the visited set
Queue<GNode> q = new ArrayDeque<>();
copy.put(node, new GNode(node.val));
q.add(node);
while (!q.isEmpty()) {
GNode u = q.poll();
for (GNode v : u.neighbors) {
if (!copy.containsKey(v)) { // first time we meet v: make its copy and explore it later
copy.put(v, new GNode(v.val));
q.add(v);
}
copy.get(u).neighbors.add(copy.get(v)); // the copied edge
}
}
return copy.get(node);
}
}C++
class Solution {
public:
GNode* cloneGraph(GNode* node) {
if (node == NULL) return NULL;
unordered_map<GNode*, GNode*> copy; // original -> its copy, also the visited set
queue<GNode*> q;
copy[node] = new GNode(node->val);
q.push(node);
while (!q.empty()) {
GNode* u = q.front();
q.pop();
for (GNode* v : u->neighbors) {
if (!copy.count(v)) { // first time we meet v: make its copy and explore it later
copy[v] = new GNode(v->val);
q.push(v);
}
copy[u]->neighbors.push_back(copy[v]); // the copied edge
}
}
return copy[node];
}
};Python
from collections import deque
from lib import GNode
class Solution:
def cloneGraph(self, node):
if node is None:
return None
copy = {node: GNode(node.val)} # original -> its copy, also the visited set
q = deque([node])
while q:
u = q.popleft()
for v in u.neighbors:
if v not in copy: # first time we meet v: make its copy and explore it later
copy[v] = GNode(v.val)
q.append(v)
copy[u].neighbors.append(copy[v]) # the copied edge
return copy[node]Common mistakes
- Returning the original nodes inside the copy.
- Creating a new copy every time a node is met.