#133

Clone Graph

Medium DFS with old → new map

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return a deep copy of a connected undirected graph, given a reference to one node.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: deep-copy a graph.

Why this works: map each original node to its copy; register the copy before visiting neighbours so cycles stop.

Example: 1 - 2 - 3 - 4 - 1 (a square)

copy 1 → copy neighbours 2 and 4 → … each node copied once

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Adding to the map after cloning neighbours — cycles then recurse forever.

Solve on LeetCode ↗
Complexity
  • Time: O(V + E).
  • Space: O(V).
Topic: Graphs
🎬 Episodes 74–85: video coming soon