sagelearnai

Clone Graph

Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #133

Given a reference to a node in a connected undirected graph, return a deep copy of the graph. Each Node has val and a list neighbors.

The tests describe a graph as an adjacency list, where entry i holds the neighbors of node i+1, and start you at node 1. They check that your copy has the same structure and shares no nodes with the original.

Examples

text
adjList = [[2,4],[1,3],[2,4],[1,3]]   →  the same structure, all new nodes
       1 —— 2
       |    |
       4 —— 3
adjList = [[]]  →  [[]]   (a single node with no neighbors)
adjList = []    →  []     (empty graph: node is null)

Hints

  1. Graphs have cycles, so a naive recursive copy would loop forever.
  2. Keep a map from each original node to its clone. If a node is already in the map, reuse the clone.

Approach

clones = {}. DFS(n):

text
if n in clones: return clones[n]
copy = Node(n.val); clones[n] = copy     # register BEFORE recursing (cycle!)
copy.neighbors = [DFS(m) for m in n.neighbors]
return copy

Registering the copy before visiting neighbors is the crux. When a cycle leads back to n, the recursion finds the half-built clone and stops. BFS works the same way: create a clone when a node is first seen, and wire its neighbors when you dequeue it.

The same "map old → new" idea solves Copy List with Random Pointer.

Complexity

Time: O(V + E). Space: O(V).

Python solution
def cloneGraph(node):
    if not node:
        return None
    clones = {node: Node(node.val)}
    stack = [node]
    while stack:
        n = stack.pop()
        for m in n.neighbors:
            if m not in clones:
                clones[m] = Node(m.val)
                stack.append(m)
            clones[n].neighbors.append(clones[m])
    return clones[node]
JavaScript solution
function cloneGraph(node) {
  const clones = new Map();
  const dfs = (n) => {
    if (!n) return null;
    if (clones.has(n)) return clones.get(n);
    const copy = new Node(n.val, []);
    clones.set(n, copy);
    for (const m of n.neighbors) copy.neighbors.push(dfs(m));
    return copy;
  };
  return dfs(node);
}