Clone Graph solution explained

Clone Graph gives you one node of a connected undirected graph, where each node stores a value and a list of neighbors, and asks for a deep copy: new node objects wired exactly like the originals. Traverse the graph with breadth-first or depth-first search and keep a hash map from each original node to its copy; create a copy the first time you meet a node and reuse it every time after. That visits each node and edge once, so the time is O(V + E).

By Published 8 min read

The problem in our words

A node has a value and a list of neighboring nodes. Edges are undirected, so if A lists B as a neighbor, B lists A. You are handed a reference to one node of a connected graph, or nothing if the graph is empty. Build a brand-new graph with the same shape: a fresh node for every original node, with the same value, whose neighbor list points at the fresh copies of the original neighbors, in the same order. Return the copy of the node you were given.

  1 ----- 2
   \     /
    \   /
      3 ----- 4

adjacency:  1: [2, 3]   2: [1, 3]   3: [1, 2, 4]   4: [3]
A small graph drawn for this page: a triangle 1-2-3 with a tail from 3 to 4

The triangle is the interesting part. Starting from node 1, a careless copy would reach 2, then 3, then come back to 1 and start copying 1 again, forever. Any correct solution has to recognize nodes it has already copied. Questions to ask first: are values unique (they usually are, but a robust answer should not depend on it), can a node list itself as a neighbor, and how big can the graph get?

What the interviewer is testing

Clone Graph checks whether you understand object identity. The returned graph must look the same but share nothing with the original, and every edge must connect copies, never a copy to an original. It also checks that you can run a traversal on a graph given only by references, without a neat list of all nodes up front. The hash map from original to copy is the single idea that makes it work, and stating that early tends to go over well.

The naive attempt, and a safe two-pass version

The tempting recursive copy creates a node and then recursively clones each neighbor. Without memory of what has been copied, it loops forever on any cycle, and every undirected edge is a cycle of length two. Adding a visited set alone is not enough either, because when you meet a visited node you still need its copy to link to.

A clear, correct starting point splits the job in two. First, traverse the graph and create one copy per original node, storing them in a map. Second, loop over the map and fill in each copy's neighbor list by looking up the copies of the original's neighbors. It is O(V + E) and easy to reason about. The one-pass version below merges the two steps.

from collections import deque


class Node:
    def __init__(self, val=0, neighbors=None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []


def clone_two_pass(start):
    if start is None:
        return None
    copies = {start: Node(start.val)}
    queue = deque([start])
    while queue:                       # pass 1: one copy per node
        node = queue.popleft()
        for nb in node.neighbors:
            if nb not in copies:
                copies[nb] = Node(nb.val)
                queue.append(nb)
    for orig, copy in copies.items():  # pass 2: wire the edges
        copy.neighbors = [copies[nb] for nb in orig.neighbors]
    return copies[start]
Python: the Node class used on this page, and the two-pass clone.

One pass: breadth-first with the map as visited set

Make a copy of the start node and put the start in a queue. Repeatedly take an original node off the queue. For each of its neighbors: if the neighbor has no copy yet, create one, record it in the map and queue the neighbor. Either way, append the neighbor's copy to the current node's copy. Because the copy is created at discovery time, a node reached again through a cycle is found in the map and simply linked. Each node is queued once and each adjacency entry is read once.

def clone_graph(start):
    if start is None:
        return None
    copies = {start: Node(start.val)}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for nb in node.neighbors:
            if nb not in copies:
                copies[nb] = Node(nb.val)
                queue.append(nb)
            copies[node].neighbors.append(copies[nb])
    return copies[start]
Python: single-pass breadth-first clone.
class Node {
  constructor(val = 0, neighbors = []) {
    this.val = val;
    this.neighbors = neighbors;
  }
}

function cloneGraph(start) {
  if (start === null || start === undefined) return null;
  const copies = new Map([[start, new Node(start.val)]]);
  const queue = [start];
  for (let head = 0; head < queue.length; head++) {
    const node = queue[head];
    for (const nb of node.neighbors) {
      if (!copies.has(nb)) {
        copies.set(nb, new Node(nb.val));
        queue.push(nb);
      }
      copies.get(node).neighbors.push(copies.get(nb));
    }
  }
  return copies.get(start);
}
JavaScript: a Map keyed by node object, so equal values never collide.

Key the map by the node object, not its value. It costs nothing extra, and it keeps the code correct if two nodes ever share a value. The JavaScript queue uses a moving head index instead of shift(), which would make each removal linear. A recursive depth-first version is also common and reads nicely: return the copy if the map has one, otherwise create it, store it, then clone each neighbor recursively and append. Store the copy before recursing, or a cycle will create duplicates. On a long chain of nodes the recursion gets as deep as the chain, so mention that limit.

Complexity

V nodes and E edges reachable from the start
ApproachTimeExtra space
Recursive copy with no memoryNever ends on a cycleUnbounded
Two passes: copy nodes, then wire edgesO(V + E)O(V) for the map and queue
One-pass BFS with the mapO(V + E)O(V)
Recursive DFS with the mapO(V + E)O(V) map plus recursion as deep as the longest path explored
V nodes and E edges reachable from the start. Scroll sideways on a small screen.

The new graph itself takes O(V + E) memory, which is unavoidable because it is the answer. The extra space in the table is on top of that.

Variations to expect

  • Directed graph. The same code works; edges are copied in whatever direction they point.
  • The graph is not connected and you get a list of all nodes. Start a traversal from every node that has no copy yet.
  • A linked list where each node also has a pointer to any other node. The same original-to-copy map handles the extra pointer. A space-saving trick interleaves each copy right after its original, then separates the two lists.
  • Clone a tree with parent pointers. Again the map prevents creating the parent twice.
  • Serialize the graph instead of cloning it. Assign each node an index during the traversal and write the adjacency list using indices.

Edge cases

  • No start node: return null or None.
  • A single node with no neighbors: one new node with an empty list.
  • A node that lists itself, if allowed: its copy must list its own copy.
  • A long chain, where a recursive version can exceed the stack.
  • Two nodes with the same value, which breaks any map keyed by value.

Mistakes that show up a lot

  • Appending the original neighbor instead of its copy, so the new graph leaks into the old one.
  • Creating the copy when a node is dequeued rather than when it is discovered, which creates two copies of nodes reached twice before processing.
  • Marking a node visited but storing its copy nowhere, then having nothing to link to.
  • Keying the map by value and silently merging distinct nodes with equal values.
  • Copying neighbors in a different order, if the checker compares lists in order.

Saying it out loud

Fictional example

Explaining identity, cycles and the map
Candidate
Every undirected edge is a little cycle, so I need to remember what I have copied. I will keep a map from each original node to its copy.
Candidate
I will run a breadth-first search. When I see a neighbor for the first time I create its copy and queue it. Either way I link the current copy to the neighbor's copy, never to the original.
Candidate
The map is keyed by node identity, so equal values cannot collide. Each node is queued once and each adjacency entry read once, so it is V plus E.
Interviewer
How would you check your answer?
Candidate
Walk both graphs in lockstep, compare values and neighbor counts, and confirm no node object appears in both.

Grids are graphs with implicit edges; Max Area of Island runs this same traversal over cells. Rotting Oranges layers a clock on top of breadth-first search, and Pacific Atlantic Water Flow runs two traversals and intersects them.

Using Natively to prepare

The tricky part of this problem is a sentence, not a line of code: say clearly that the map stores copies and is keyed by identity. In practice, Natively can read the prompt and any starter code from a screenshot on Mac or Windows, propose a traversal with the copy map in your language, and transcribe your mock explanation so you can review it afterward. See how the interview assistant works.

Questions people ask

How do you solve Clone Graph?

Traverse from the given node with BFS or DFS while keeping a map from each original node to its copy. Create a copy the first time a node is discovered, and append the copy of each neighbor, never the original, to the current node's copy.

What is the time complexity of Clone Graph?

O(V + E) for V nodes and E edges, since each node is queued once and each adjacency entry is read once. The map and queue take O(V) extra space on top of the new graph.

Why does a plain recursive copy loop forever?

In an undirected graph every edge leads back to where it came from, so a copy that does not remember what it already copied keeps revisiting the same nodes. The original-to-copy map both stops the loop and provides the copy to link to.

Should the map be keyed by node value?

Key it by the node object instead. Values are often unique in the usual version, but keying by identity costs nothing and keeps the clone correct when two nodes share a value.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP