Clone Graph

Quick Overview

Given a reference to a node in a connected undirected graph, return a deep copy of the graph. Tests graph traversal and hash map usage, a recurring Meta interview question.

Meta
Coding & Algorithms
Software Engineer
Meta
Software Engineer
Onsite
Coding & Algorithms
Medium

0


Given a reference to a node in a connected undirected graph, return a deep copy of the graph. Tests graph traversal and hash map usage, a recurring Meta interview question.

Meta asks Clone Graph in onsite coding rounds to test graph traversal and the old-to-new node mapping that prevents infinite loops on cycles. The interviewer looks for a correct deep copy with no shared references and a clear explanation of why the hash map is needed.

What the Interviewer Expects
  • Use a hash map from original node to cloned node to handle cycles and shared neighbors
  • Traverse with DFS or BFS and copy each node exactly once
  • Wire neighbor lists to cloned nodes, never originals
  • State O(V + E) time and O(V) space
  • Handle a None input and a single node with no neighbors
  • Mention recursion depth and offer an iterative BFS for very large graphs
Key Topics to Cover
Graph traversal
DFS and BFS
Hash map memoization
Deep copy
Cycle handling
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you write it iteratively with BFS to avoid recursion limits?
  • How would you clone a graph that is not connected, given a list of all nodes?
  • How would you clone a directed graph with weighted edges?
  • How would you verify that the copy is deep and structurally identical?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Problem Analysis

The problem requires us to create a deep copy of an undirected graph, which means we need to replicate both nodes and their connections (edges). This is a classic case for the graph traversal patt...

Approach
  1. Initialization: Start by creating a hash map (dictionary in Python) to keep track of already copied nodes. This will help in avoiding cycles and redundant copies.
  2. Recursive Function: Def...

Submit Your Answer
Markdown supported