Clone Graph
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Use a HashMap to track visited nodes and their clones (BFS or DFS).
Why Interviewers Ask This
Salesforce interviewers ask this to evaluate a candidate's mastery of graph traversal algorithms and memory management. They specifically test your ability to handle cycles in undirected graphs without creating infinite loops, while ensuring a true deep copy rather than a shallow reference. This assesses your understanding of HashMap usage for state tracking and your capacity to write clean, production-ready code under pressure.
How to Answer This Question
Key Points to Cover
- Explicitly mention using a HashMap to track visited nodes and prevent infinite loops caused by cycles
- Demonstrate clear distinction between shallow copy (reference) and deep copy (new objects)
- Select BFS or DFS with a reasoned justification regarding memory safety or implementation complexity
- Handle edge cases like null inputs or single-node graphs proactively
- Explain the logic for linking neighbors in the cloned graph during traversal
Sample Answer
Common Mistakes to Avoid
- Creating a shallow copy instead of a deep copy, resulting in shared references between original and cloned graphs
- Failing to detect cycles, causing the algorithm to enter an infinite loop when traversing undirected edges
- Using recursion without considering stack depth limits, which can crash on large graphs common in enterprise systems
- Neglecting to initialize the map with the starting node before beginning the traversal loop
Practice This Question with AI
Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.