Problem
Return a deep copy of a connected undirected graph. Each node has an integer value and a list of neighbours. Node values are unique.
Original: LeetCode 133: Clone Graph.
Examples
Example 1
`adjList = [[2, 4], [1, 3], [2, 4], [1, 3]]``[[2, 4], [1, 3], [2, 4], [1, 3]]`Same shape, but every node in the answer is a new object.
Example 2
`adjList = []``[]`A null input returns null.
Constraints
- The number of nodes in the graph is in the range
[0, 100]. 1 <= Node.val <= 100Node.valis unique for each node.- There are no repeated edges and no self-loops in the graph.
- The Graph is connected and all nodes can be visited starting from the given node.
Hints
Hint 1
A deep copy means new node objects, with the same values and the same adjacency shape. The graph can contain cycles, so a naive recursion without a map would loop forever.
Hint 2
Copying a graph is a traversal plus a map from old node to new node.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. There is no useful slower method; you must visit every node and every edge once.
Optimal. DFS or BFS with a HashMap<Node, Node>. Create the clone on first visit, then copy the neighbour list after the neighbours themselves have clones.
Alternative. BFS with a queue is the same algorithm, just iterative.
Complexity
- Time
- O(V + E)
O(V + E) time and O(V) space for the map and the recursion or queue.
- Space
- O(V)
Code
class Node:
def __init__(self, val: int = 0, neighbors: list["Node"] | None = None) -> None:
self.val = val
self.neighbors = neighbors if neighbors is not None else []
def clone_graph(node: Node | None) -> Node | None:
copies: dict[Node, Node] = {}
def clone(n: Node) -> Node:
if n in copies:
return copies[n]
copies[n] = Node(n.val)
copies[n].neighbors = [clone(nei) for nei in n.neighbors]
return copies[n]
return clone(node) if node else None
if __name__ == "__main__":
n1, n2, n3, n4 = Node(1), Node(2), Node(3), Node(4)
n1.neighbors, n2.neighbors = [n2, n4], [n1, n3]
n3.neighbors, n4.neighbors = [n2, n4], [n1, n3]
c1 = clone_graph(n1)
assert c1 is not n1 and c1.val == 1 and len(c1.neighbors) == 2
c2 = next(n for n in c1.neighbors if n.val == 2)
assert c2 is not n2 and c1 in c2.neighbors
assert clone_graph(None) is None
print("ok")import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CloneGraph {
static class Node {
int val;
List<Node> neighbors = new ArrayList<>();
Node(int val) { this.val = val; }
}
static Node cloneGraph(Node node) {
if (node == null) return null;
return clone(node, new HashMap<>());
}
static Node clone(Node node, Map<Node, Node> copies) {
var cached = copies.get(node);
if (cached != null) return cached;
var copy = new Node(node.val);
copies.put(node, copy);
for (var nei : node.neighbors) copy.neighbors.add(clone(nei, copies));
return copy;
}
public static void main(String[] args) {
Node n1 = new Node(1), n2 = new Node(2), n3 = new Node(3), n4 = new Node(4);
n1.neighbors.addAll(List.of(n2, n4));
n2.neighbors.addAll(List.of(n1, n3));
n3.neighbors.addAll(List.of(n2, n4));
n4.neighbors.addAll(List.of(n1, n3));
Node c1 = cloneGraph(n1);
if (c1 == n1 || c1.val != 1 || c1.neighbors.size() != 2) throw new AssertionError();
Node c2 = c1.neighbors.get(0).val == 2 ? c1.neighbors.get(0) : c1.neighbors.get(1);
Node c4 = c1.neighbors.get(0).val == 4 ? c1.neighbors.get(0) : c1.neighbors.get(1);
if (c2 == n2 || c4 == n4 || c2.val != 2 || c4.val != 4) throw new AssertionError();
if (!c2.neighbors.contains(c1) || !c4.neighbors.contains(c1)) throw new AssertionError();
if (cloneGraph(null) != null) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample is the four-node square: 1 is connected to 2 and 4, 2 to 1 and 3, 3 to 2 and 4, and 4 to 1 and 3. The clone must not share node objects with the original.
- A null input returns null. A single node with no neighbours copies as one isolated node.
Follow-ups
- Copy List with Random Pointer is the same map idea on a linked list.
- If node values were not unique, the map must key on identity, which it already does.
Interview script
"I keep a map from original node to clone so cycles do not loop and so neighbour pointers can be wired to the new objects. I create the clone the first time I see a node, then copy its neighbour list recursively."
Source: LeetCode 133: Clone Graph
Sources (1)
- LeetCode 133: Clone Graphleetcode.com