Clone Graph
Clone Graph
Section titled “Clone Graph”
Medium
Day 6 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Return a deep copy (clone) of a connected undirected graph. Each node contains a value and a list of its neighbors.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
adjList = [[2,4],[1,3],[2,4],[1,3]] - Output:
[[2,4],[1,3],[2,4],[1,3]]
Example 2:
- Input:
adjList = [[]] - Output:
[[]]
Constraints:
0 ≤ nodes ≤ 100Node.val is unique.
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Tests deep copy of complex graph structures while handling cycles.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Pattern: Deep Copy with Map
Use a hash map to track already-cloned nodes. Handle cycles by returning existing clones.
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD Start["Start Node / Grid Cell"] --> Q["Initialize Queue / Stack / Visited Set"] Q --> Loop{"Is Queue / Stack Empty?"} Loop -- "No" --> Pop["Pop Current Node / Cell"] Pop --> Check{"Check Destination / Target"} Check -- "Found" --> Done["Return Path / Result"] Check -- "Not Found" --> Nbrs["Explore Neighbors (4-directions / Adjacency)"] Nbrs --> Push["Push Unvisited Neighbors"] Push --> Loop Loop -- "Yes" --> Done🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”// Must traverse graph, no brute force- Time Complexity:
O(V+E) - Space Complexity:
O(V) - Explanation: DFS with visited map.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function cloneGraph(node) { if (!node) return null; const visited = new Map(); function dfs(node) { if (visited.has(node)) return visited.get(node); const clone = new Node(node.val); visited.set(node, clone); for (const neighbor of node.neighbors) { clone.neighbors.push(dfs(neighbor)); } return clone; } return dfs(node);}- Time Complexity:
O(V+E) - Space Complexity:
O(V) - Explanation: DFS with a visited map to handle cycles.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”- Cycles make naive recursion infinite loop
- Use hash map: original → clone
- Check map before recursing on neighbors
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Use a hash map for cloned nodes.
- If a node is already cloned, return the clone (handles cycles).
- Recursively clone neighbors.