Skip to the solution
MediumDSA15 min read

How do you clone a graph?

257 views

The problem

Question presented to candidate: "You get a reference to one node of a connected, undirected graph. Each node has a value and a list of its neighbours. Return a deep copy of the whole graph β€” every node must be a new object, wired up the same way. Please write it in Python and tell me the complexity."

What a strong answer should cover:

  • A traversal (BFS with a queue or DFS with recursion) plus a dict mapping each original node β†’ its copy; the map is both the visited set and the way to find the copy of a neighbour.
  • Why the map is mandatory: graphs have cycles, so copying without it loops forever (or duplicates nodes).
  • Inserting the copy into the map before visiting its neighbours, and handling the empty input (None).
  • O(V + E) time and O(V) extra space for the map and the queue (or the recursion stack).
  • Python specifics: collections.deque with popleft() for the queue (not list.pop(0)), node objects are hashable by identity unless the class defines __eq__ without __hash__, and recursive DFS hits the default recursion limit of 1000 on a long path.

Clarifying questions expected:

  • Is the input possibly None, and is everything reachable from the given node?
  • How big can the graph be (is recursion safe)?

Code / implementation expected: Yes β€” a clone_graph(node) function in Python using BFS or DFS with a dict, plus a check that the copy shares no node with the original.

  • graphs
  • hashing
  • bfs

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read Β· 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBFS clone with an old-to-new map: shape check and no shared nodes
PythonWhy the map matters: naive recursion vs DFS clone call counts, and BFS on a 10000-node path

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 109 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you count the number of islands in a grid?

Continue