Introduction
Clone Graph is one of the most important Graph Traversal interview problems.
You are given:
Connected GraphGoal:
Create a deep copy of the graph. Requirements:
New Nodes
New EdgesSame Structure
Example
1 -- 2| |
4 -- 3
Output:
Cloned Graph1 -- 2
| |
4 -- 3
Key Observation
Each original node should map to:
Exactly one cloned node. Use:
Hash Maporiginal → clone
to avoid:
Duplicate nodes Infinite loops Algorithm
1. Create clone node.
2. Store in map.
3. Traverse neighbors.
4. Clone neighbors.
5. Connect cloned edges.DryRun
Input:
1 → [2,4]
2 → [1,3]
3 → [2,4]4 → [1,3]
Mapping:
1 → clone1
2 → clone2
3 → clone34 → clone4
Answer:
Deep Copy Created Approach : DFS
Explanation
For every node:
- Check map.
- If already cloned, return clone.
- Create new clone.
- Clone all neighbors.
- Connect neighbors.