By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
"This problem tests your ability to traverse and reconstruct a graph—if you nail it, you prove you can handle recursion, cycles, and deep copies, which are core skills for system design and distributed systems interviews at FAANG."
Before attempting this problem, you must understand: 1. Graph Traversal (DFS/BFS) – How to visit every node in a graph. 2. Hash Maps (Dictionaries) – For O(1) lookups and tracking visited nodes. 3. Recursion vs. Iteration – When to use each for graph traversal.
cloneGraph(node, visited)
queue = deque([node])
visited = {node: clone}
new_node = Node(node.val)
new_node.neighbors = [visited[n] for n in node.neighbors]
Follow these steps every time you solve a "Clone a Graph" problem:
val
neighbors
Output: A deep copy of the entire graph (new nodes, not references).
Handle Edge Cases
node is None
None
If the graph has only one node (no neighbors), return a new node with the same value.
Choose Traversal (DFS or BFS)
BFS (Iterative): Better for wide graphs, avoids recursion stack issues.
Initialize a Visited Map
Prevents cycles and redundant work.
Traverse & Clone Nodes
Store the mapping in visited.
visited
Reconstruct Edges
For each neighbor of the original node, add the cloned neighbor to the new node’s neighbors list.
Return the Cloned Graph
Problem: Clone an undirected graph where each node has a val and a list of neighbors.
Solution:
class Node: def __init__(self, val=0, neighbors=None): self.val = val self.neighbors = neighbors if neighbors is not None else [] def cloneGraph(node: 'Node') -> 'Node': if not node: return None visited = {} # Maps original node → cloned node def dfs(original_node): if original_node in visited: return visited[original_node] # Clone the node clone = Node(original_node.val) visited[original_node] = clone # Clone all neighbors for neighbor in original_node.neighbors: clone.neighbors.append(dfs(neighbor)) return clone return dfs(node)
Time Complexity: O(V + E) (visits every node and edge once). Space Complexity: O(V) (visited map + recursion stack).
Why This Works: - DFS ensures we visit every node exactly once. - The visited map prevents cycles and redundant cloning. - Recursion naturally handles the traversal order.
Problem: Same as above, but implement it iteratively (BFS).
from collections import deque def cloneGraph(node: 'Node') -> 'Node': if not node: return None visited = {} queue = deque([node]) visited[node] = Node(node.val) # Clone the first node while queue: original_node = queue.popleft() for neighbor in original_node.neighbors: if neighbor not in visited: visited[neighbor] = Node(neighbor.val) # Clone neighbor queue.append(neighbor) # Add the cloned neighbor to the current node's neighbors visited[original_node].neighbors.append(visited[neighbor]) return visited[node]
Time Complexity: O(V + E) (same as DFS). Space Complexity: O(V) (visited map + queue).
Why This Works: - BFS avoids recursion stack limits. - The queue ensures we process nodes level by level. - The visited map still prevents cycles.
Problem: Clone a graph where each node has a random pointer (like in "Copy List with Random Pointer").
random
class Node: def __init__(self, val=0, neighbors=None, random=None): self.val = val self.neighbors = neighbors if neighbors is not None else [] self.random = random def cloneGraph(node: 'Node') -> 'Node': if not node: return None visited = {} def dfs(original_node): if original_node in visited: return visited[original_node] clone = Node(original_node.val) visited[original_node] = clone for neighbor in original_node.neighbors: clone.neighbors.append(dfs(neighbor)) # Handle random pointer if original_node.random: clone.random = dfs(original_node.random) return clone return dfs(node)
Time Complexity: O(V + E) (same as before). Space Complexity: O(V) (visited map + recursion stack).
Why This Works: - The random pointer is treated like another neighbor. - DFS ensures all pointers (neighbors + random) are cloned correctly.
if not node: return None
"Alright, let’s lock this in. To clone a graph, you need three things: a traversal method (DFS or BFS), a visited map to avoid cycles, and a way to reconstruct edges. Start by handling edge cases—empty graph, single node. Then, pick DFS or BFS. DFS is simpler, but BFS avoids recursion limits. Use the visited map to track cloned nodes. For each node, clone it, then clone its neighbors. Finally, reconnect the edges. Common pitfalls? Forgetting the visited map, shallow copying, or missing neighbors. If the interviewer throws in a random pointer, treat it like another neighbor. You’ve got this—now go ace that interview!
This framework ensures you never blank on a "Clone a Graph" problem in an interview. Good luck! ?
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.