mediumGraphsGraphs

Clone Graph

mediumTime: O(V + E)Space: O(V)

Signals to notice

deep copy a graphhandle cyclesmap original to clone

Brute force first

No simpler alternative — you must handle cycles in any approach. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

BFS or DFS with a hash map from original node → cloned node. When you encounter a node already in the map, reuse the clone instead of creating a new one. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

The hash map guarantees each node is cloned exactly once. When you reach a node you've already cloned, you connect to the existing clone — this correctly handles cycles. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Not handling cycles — without the visited map, a cycle causes infinite recursion or infinite queue growth. The map serves dual purpose: visited tracking and clone lookup. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Graphs Pattern