Clone Graph
Make a deep copy of a connected undirected graph, using a map from each original node to its copy.
The problem
You get one node of a connected undirected graph, where each node has an integer val and a list of neighbors. Return a deep copy of the whole graph: brand new nodes with the same values and the same connections, sharing no node with the original. In the examples the graph is an adjacency list where entry i lists the neighbors of the node with value i + 1, and you receive the node with value 1.
Input adjList = [[2, 3], [1, 3], [1, 2, 4], [3]]
Output [[2, 3], [1, 3], [1, 2, 4], [3]]
A triangle of nodes 1, 2 and 3, with node 4 hanging off node 3. The copy has the same shape, built from new nodes.
Input adjList = [[2], [1]]
Output [[2], [1]]
Two nodes joined by one edge.
Key constraint: The graph can contain cycles, so the same node can be reached along many paths, yet each node must be copied exactly once.
How to spot the pattern
- You have to visit every node reachable from a starting node.
- Cycles mean you must remember which nodes you have already handled.
- Each new node must link to the copies of its neighbors, never to the originals.
The idea
Walk the graph with DFS and keep a map from each original node to its copy. When you reach a node, create its copy and put it in the map first, and only then copy its neighbors. If a neighbor is already in the map, reuse its copy instead of visiting it again; that one check handles both cycles and shared neighbors.
Brute force: Copy each node and recurse into its neighbors without remembering what you copied, which never finishes once the graph has a cycle.
Step by step
- 1If the input node is
null, returnnull. - 2Keep a map from each original node to its copy.
- 3To clone a node: if it is already in the map, return its copy.
- 4Otherwise create a copy with the same value and store it in the map before going any further.
- 5Clone each neighbor the same way, add the result to the copy's neighbor list, and return the copy.
See the pattern move
The graph bfs and dfs pattern on a small example. Step through it, or press play.
Code
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
copies = {} # original node -> its copy
def clone(original: 'Node') -> 'Node':
if original in copies:
return copies[original]
copy = Node(original.val)
copies[original] = copy # save it before the neighbors, so a cycle stops here
for neighbor in original.neighbors:
copy.neighbors.append(clone(neighbor))
return copy
return clone(node) if node else NoneComplexity
Time
O(V + E)
Space
O(V)
Every node is copied once and every edge is followed once from each end; the map and the recursion stack hold up to V nodes.
Watch out for
- Adding the copy to the map only after cloning its neighbors, which recurses forever around a cycle.
- Linking a copy to an original neighbor instead of to that neighbor's copy.
- Forgetting the empty graph, where the input node is null.
Follow-up questions
Can you do it without recursion?
Yes, use BFS with a queue: create a node's copy the first time you see it, and connect neighbor copies as you take each node off the queue.
What if the graph might not be connected?
One starting node can't reach every part, so you need the full list of nodes and run the same clone from each node that has no copy yet.
In Hinglish
Har original node ka copy map mein rakho. Pehle copy banao aur map mein daalo, phir neighbours clone karo; jo map mein pehle se hai, usse dobara mat banao.