Clone Graph

Difficulty: Medium

You're given a node in a connected undirected graph. Each node has a value and a list of its neighbors.

Make a deep copy of the whole graph. Every node must be a new object, but the copy must have the same values and the same connections.

Examples

Input: adjacency list = [[2,4],[1,3],[2,4],[1,3]] (node 1 connects to 2 and 4, node 2 connects to 1 and 3, etc.)
Output: [[2,4],[1,3],[2,4],[1,3]]

The copy has the same four nodes with the same connections, but every node object is a new one, distinct from the original.

Input: adjacency list = [[]]
Output: [[]]

A single node with no neighbors - the copy is a single new node, also with no neighbors.

Input: adjacency list = []
Output: []

An empty graph copies to an empty graph.

Approach

This is a graph traversal with a twist: instead of just marking a node "visited," remember its copy. Other nodes' neighbor lists must point to that same copy, and cycles mean you must never clone a node twice.

Use a hash map from original node to clone. Traverse from the given node (DFS or BFS). The first time you see a node, create its clone and store it in the map before visiting its neighbors. Then, if a neighbor loops back to it, you find the clone in the map instead of cloning again.

As you visit each node, link the clones of its neighbors into its clone's neighbor list.

Solutions

DFS - Recursive with a Clone Map

Visit each node recursively. The first time you see a node, create its clone and add it to the map. Then recurse into its neighbors and attach each neighbor's clone (existing or new) to this clone's neighbor list.

function cloneGraph(node) {
  if (!node) return null;

  const visited = new Map(); // original node -> cloned node

  function dfs(original) {
    if (visited.has(original)) {
      return visited.get(original);
    }

    const clone = { val: original.val, neighbors: [] };
    visited.set(original, clone);

    for (const neighbor of original.neighbors) {
      clone.neighbors.push(dfs(neighbor));
    }

    return clone;
  }

  return dfs(node);
}

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

BFS - Iterative with a Clone Map

Clone the starting node first, then use a queue to visit each original node once. For each popped node, go through its neighbors: clone and enqueue any new neighbor, then link the neighbor's clone into the current node's clone.

function cloneGraph(node) {
  if (!node) return null;

  const visited = new Map();
  visited.set(node, { val: node.val, neighbors: [] });
  const queue = [node];

  while (queue.length > 0) {
    const current = queue.shift();

    for (const neighbor of current.neighbors) {
      if (!visited.has(neighbor)) {
        visited.set(neighbor, { val: neighbor.val, neighbors: [] });
        queue.push(neighbor);
      }
      visited.get(current).neighbors.push(visited.get(neighbor));
    }
  }

  return visited.get(node);
}

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