DSA Graphs

Clone Graph

BFS or DFS with a hash map from original node to clone — copy nodes lazily, link neighbors as discovered.

Medium
Time O(V + E) Space O(V)
LeetCode
3 min read
graph bfs dfs hashing

Problem#

Given a reference to a node in a connected undirected graph, return a deep copy of the graph.

Examples#

  • 4-node cycle 1 — 2 — 3 — 4 — 1 → an isomorphic deep copy.
  • Single node with no neighbors → a deep copy of just that node.
  • nullnull.

Constraints#

  • The number of nodes is in [0, 100]. Node values are unique.

Approach#

DFS with a map<Node*, Node*> from original to clone. On visiting a node, if it’s already in the map, return its clone. Else, create the clone, register it, and recursively clone every neighbor.

Solution#

Clone Graph
class Solution {
public:
Node* cloneGraph(Node* node) {
if (!node) return nullptr;
unordered_map<Node*, Node*> map;
function<Node*(Node*)> dfs = [&](Node* u) -> Node* {
auto it = map.find(u);
if (it != map.end()) return it->second;
Node* c = new Node(u->val);
map[u] = c;
for (Node* nb : u->neighbors) c->neighbors.push_back(dfs(nb));
return c;
};
return dfs(node);
}
};

Editorial#

The map both detects cycles and serves as the lookup for “have we cloned this yet?”. Insert into the map before recursing into neighbors — otherwise the cycle would cause infinite recursion. Each edge is traversed twice (once from each endpoint), giving O(V + E).

Complexity#

  • Time: O(V + E).
  • Space: O(V) for the map plus recursion stack.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.