Clone Graph

Return a deep copy of a connected undirected graph.

Pattern

DFS + Hash Map

This problem follows the DFS + Hash Map pattern, commonly found in the Graphs category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

DFS traversal. Use a hash map to track original-to-clone mapping. Clone neighbors recursively.

Key Insight

The hash map serves double duty: it prevents infinite loops in cycles AND ensures each node is cloned exactly once.

Step-by-step

  1. 1Use a hash map to store original-node -> cloned-node mapping
  2. 2Start DFS from the given node
  3. 3If a node is already cloned (in the map), return its clone
  4. 4Otherwise, create a clone and recursively clone all neighbors

Pseudocode

cloned = {}
def cloneGraph(node):
    if not node: return null
    if node in cloned: return cloned[node]
    clone = Node(node.val)
    cloned[node] = clone
    for neighbor in node.neighbors:
        clone.neighbors.append(cloneGraph(neighbor))
    return clone
Complexity Analysis

Time Complexity

O(V + E)

Space Complexity

O(V)
More Graphs Problems

Master this pattern with YeetCode

Practice Clone Graph and similar Graphs problems with flashcards. Build pattern recognition through active recall.

Practice this problem