133. Clone Graph
Asked at 18Meta71Amazon40Google40Bloomberg28Microsoft23Apple22Pocket Gems100Flexport98Wix87Siemens65CrowdStrike65MongoDB61Nutanix60eBay53Uber50ByteDance50Nvidia39Oracle35
Problem
Given a reference to one node of a connected undirected graph, where each node has a val and a list of neighbors, return a deep copy of the whole graph.
Example: the 4-cycle 1–2–3–4–1 → an identical, independent 4-cycle
Constraints: up to 100 nodes; values are unique.
DFS with a map original → clone. Create the clone before recursing into neighbours so cycles resolve through the map.
Complexity: O(V + E).
class Node: # provided by LeetCode
def __init__(self, val=0, neighbors=None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
class Solution:
def cloneGraph(self, node: Optional["Node"]) -> Optional["Node"]:
clones = {}
def dfs(n):
if n in clones:
return clones[n]
c = clones[n] = Node(n.val)
c.neighbors = [dfs(nb) for nb in n.neighbors]
return c
return dfs(node) if node else None
ns = [Node(i) for i in range(1, 5)]
for i, nbs in enumerate([[2, 4], [1, 3], [2, 4], [1, 3]]):
ns[i].neighbors = [ns[j - 1] for j in nbs]
c = Solution().cloneGraph(ns[0])
assert c is not ns[0] and [n.val for n in c.neighbors] == [2, 4]
assert c.neighbors[0].neighbors[0] is c # cycle preserved
class Node { // provided by LeetCode
public int val;
public List<Node> neighbors = new ArrayList<>();
public Node(int val) { this.val = val; }
}
class Solution {
private final Map<Node, Node> clones = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) return null;
if (clones.containsKey(node)) return clones.get(node);
Node c = new Node(node.val);
clones.put(node, c);
for (Node nb : node.neighbors) c.neighbors.add(cloneGraph(nb));
return c;
}
}
type Node struct { // provided by LeetCode
Val int
Neighbors []*Node
}
func cloneGraph(node *Node) *Node {
clones := map[*Node]*Node{}
var dfs func(*Node) *Node
dfs = func(n *Node) *Node {
if c, ok := clones[n]; ok {
return c
}
c := &Node{Val: n.Val}
clones[n] = c // register before recursing: the graph has cycles
for _, nb := range n.Neighbors {
c.Neighbors = append(c.Neighbors, dfs(nb))
}
return c
}
if node == nil {
return nil
}
return dfs(node)
}