Clone Graph
Return a deep copy of the connected undirected graph reachable from node.
Clone Graph is the canonical visited-map problem: as you DFS, a map from old node to new node both stops infinite loops and wires up the copied edges. Skip the map and a cycle sends you spinning forever. Once you see why one structure does double duty, most graph-copy problems collapse into it.
Examples
You write
clone_graph(node: Optional['Node'])
Example 1
- Input
- [[2,4],[1,3],[2,4],[1,3]]
- returns
- [[2,4],[1,3],[2,4],[1,3]]
Example 2
- Input
- [[]]
- returns
- [[]]
The pattern behind it
Graphs
I reach for it when
- The input is edges, prerequisites or connections.
- You need cycles, an ordering or connected groups.
Say this before you type. Say whether the edges are directed, and which of the three jobs you are doing.
All 32 Graphs problemsBFS & DFS
I reach for it when
- You walk a grid, a graph or a tree and visit each cell once.
- The word shortest appears and every step costs the same.
Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.
All 52 BFS & DFS problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.