7 min readRishi

Clone Graph: Copy Nodes Without Falling Into the Cycle

In this series: Interview patterns in Python

Clone Graph: Copy Nodes Without Falling Into the Cycle

"Clone Graph" is the moment an interviewer finds out whether you have only cloned trees. A tree copy is a recursion with a null base case. An undirected graph has cycles; recurse without a map and you infinite-loop, or you emit two clones of the same node and the copy is a different shape. The problem is LeetCode 133, and it is a Graph BFS (or DFS) pattern with an identity table.

Trees hide the map

Each node has a val and a list of neighbors. The graph is undirected, connected from the given node, and nodes have unique values in the usual statement. Return a deep copy: new node objects, same connectivity, no shared references with the original.

Input:  1 -- 2
        |    |
        4 -- 3
Output: a new 1--2--3--4 cycle, disjoint in memory.

You must visit every node and every edge once, and you must not create a second clone when you see a node again via another edge. That second requirement is the map: original -> clone. First time you see a node, allocate the clone and record it; every later time, reuse it when wiring neighbors. Trees hide this because there is only one parent pointer inbound.

Say the map out loud before you code. Do not copy neighbor lists by value (clone.neighbors = node.neighbors). That aliases the original graph and fails any interviewer who checks is.

BFS with an identity table

Seed the queue and the map with the clone of the start. For each dequeued original, iterate neighbors: if a neighbor is not in the map, clone it, map it, enqueue it; then append map[neighbor] to map[current].neighbors.

from collections import deque

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

def clone_graph(node: Node | None) -> Node | None:
    if node is None:
        return None

    clones = {node: Node(node.val)}
    q = deque([node])

    while q:
        cur = q.popleft()
        for nbr in cur.neighbors:
            if nbr not in clones:
                clones[nbr] = Node(nbr.val)
                q.append(nbr)
            clones[cur].neighbors.append(clones[nbr])

    return clones[node]

Empty input: return None. Single node with no neighbors: one new node, empty list. A self-loop (rare in the stock prompt, fair as a follow-up): the map already contains the node, so you append the clone to its own neighbors — which is what you want.

The enqueue belongs inside the if nbr not in clones block. Creating the neighbor clone but forgetting to enqueue it is the bug that copies the first layer and leaves the rest as stubs with empty neighbor lists.

Walk the 1-2-3-4 cycle

Label the adjacency the way the square is usually drawn:

1: [2, 4]
2: [1, 3]
3: [2, 4]
4: [1, 3]

Start at 1. After the seed, clones is {1: 1'} and the queue is [1].

Dequeue 1. Neighbor 2 is new: allocate 2', enqueue 2, append 2' to 1'.neighbors. Neighbor 4 is new: allocate 4', enqueue 4, append 4' to 1'.neighbors. Queue is [2, 4]. Map holds 1, 2, 4.

Dequeue 2. Neighbor 1 is already in the map: append 1' to 2'.neighbors. Do not allocate a second 1'. Neighbor 3 is new: allocate 3', enqueue 3, append 3' to 2'.neighbors. Queue is [4, 3].

Dequeue 4. Neighbors 1 and 3 are both in the map. Append 1' and 3' to 4'.neighbors. Nothing new is enqueued.

Dequeue 3. Neighbors 2 and 4 are both in the map. Append 2' and 4' to 3'.neighbors. Queue is empty.

The copy is 1'—2'—3'—4' with the same undirected edges. 1' is 1 is false. 1'.neighbors[0] is 2 is false. If either is is true, you aliased. Two edges into the same node are one clone.

DFS is the same map

The recursive function creates, stores, then fills neighbors from recursive calls. Write it. Do not wave at "DFS is similar."

def clone_graph_dfs(node: Node | None) -> Node | None:
    if node is None:
        return None

    clones: dict[Node, Node] = {}

    def dfs(cur: Node) -> Node:
        if cur in clones:
            return clones[cur]
        copy = Node(cur.val)
        clones[cur] = copy
        copy.neighbors = [dfs(nbr) for nbr in cur.neighbors]
        return copy

    return dfs(node)

Store the clone before you walk neighbors. If you walk first and store after, the cycle 1 → 2 → 1 calls dfs(1) a second time while 1 is not in the map, allocates a second 1', and never returns. That is the infinite recursion the map exists to stop.

Both versions are O(V + E). Space is O(V) for the map, plus the queue or the call stack. Prefer BFS if you have already used recursion on a previous question and the interviewer looks bored. Prefer DFS if you want fewer moving parts. Do not mix the two mid-answer.

Disconnected input

The stock problem gives you one node and promises the graph is connected from there. The follow-up is a graph with two components. A single BFS from node clones that component and never sees the other.

Say you would take the full node list, not a single source. Iterate every node as a potential start. Skip nodes already in the map. The same clones dictionary is the visited set.

def clone_graph_all(nodes: list[Node]) -> list[Node]:
    clones: dict[Node, Node] = {}

    def clone_from(start: Node) -> None:
        if start in clones:
            return
        clones[start] = Node(start.val)
        q = deque([start])
        while q:
            cur = q.popleft()
            for nbr in cur.neighbors:
                if nbr not in clones:
                    clones[nbr] = Node(nbr.val)
                    q.append(nbr)
                clones[cur].neighbors.append(clones[nbr])

    for n in nodes:
        clone_from(n)
    return [clones[n] for n in nodes]

You need the list of nodes from somewhere. Do not pretend clone_graph(node) can find a component it cannot reach. An isolated node in that list is the single-node case again.

Do not hash on val

The usual statement says values are unique. The general solution still keys the map on the node object, not on val.

Hashing on val fails the moment the follow-up drops uniqueness. Two nodes with val == 1 collapse to one clone. The copy loses a vertex. It also fails if you clone first and then mutate val on the copy. The original object is the key. The integer never was.

# Wrong once values are not unique
clones_by_val = {node.val: Node(node.val)}

# Right: identity of the original object
clones = {node: Node(node.val)}

If you must key on val because the prompt guarantees uniqueness and they asked for a dict of ints, say the guarantee out loud. Then key on val. Without that sentence, use the object.

What they ask next

Random pointer lists (Copy List with Random Pointer) are the same map on a different shape. Time is O(V + E). Space is O(V).

Skip this machinery when they said the graph is a tree — a parent pointer and a null base case are enough — or when they want a copied adjacency matrix. That is a nested list copy, not node identity.

Whiteboard checklist: empty input, single node, the square with the four map insertions said out loud, self-loop uses the existing clone, disconnected needs the full list, keys are nodes not vals, clone.neighbors is node.neighbors is false.

This is Graph BFS with an identity table. More graph problems live in the Technical Interview category.

Keep reading

Newsletter

New posts, straight to your inbox

One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.

Comments

  • No comments yet. Be the first.