InterviewPrepKit

Home / Coding / Graphs

Clone Graph

medium Original β†—
Solving tips
  • Core technique: traverse (DFS or BFS) while keeping an original-node -> clone hash map that doubles as the visited set, so cycles terminate.
  • Record a node's clone in the map the INSTANT you create it, BEFORE recursing into neighbors; otherwise a cycle re-enters the node and infinite-loops.
  • Key on the node object, not on val (habit that survives duplicate-value variants), and handle the node is None empty-graph case.
  • Target O(V+E) time, O(V) space; prefer BFS/iterative when recursion depth could be a concern.

Problem

You’re given a reference to a node in a connected, undirected graph. Each node holds an integer val and a list of its neighbors. Return a deep copy of the whole graph: a brand-new set of nodes with the same values and the same connectivity, sharing no objects with the original.

The graph is described for testing with an adjacency list (1-indexed), but your function receives only the single starting node. Values are unique and, by convention, the i-th node has val = i. An empty graph (a None start node) must return None.

Node definition:

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

Examples

  • adjList = [[2,4],[1,3],[2,4],[1,3]] β†’ a 4-node cycle 1–2–3–4–1, deep-copied. Node 1’s clone links to clones of 2 and 4, and none of the returned objects are the originals.
  • adjList = [[]] β†’ one node with value 1 and no neighbors β†’ a single fresh isolated node.
  • adjList = [] β†’ empty graph β†’ return None.

Constraints

  • Number of nodes is in [0, 100].
  • 1 <= Node.val <= 100, all values unique.
  • The graph is connected and undirected (every edge appears in both endpoints’ lists); no self-loops, no repeated edges.

Think about it first

Hint 1 This is a traversal (DFS or BFS) plus bookkeeping. The hard part isn't visiting nodes β€” it's making sure each original node is cloned exactly once, even though it's reachable along several paths in a cyclic graph.
Hint 2 Keep a hash map from original node β†’ its clone. Before recursing into a neighbor, check the map: if the neighbor already has a clone, reuse it; otherwise create and record it, then recurse. This map doubles as your "visited" set, so cycles terminate.
Hint 3 DFS: clone the current node, put it in the map immediately (so a cycle back to it finds it), then for each neighbor append the (recursively obtained) clone. BFS is the same idea with a queue: create a node's clone when you first see it, and wire up edges as you pop each node.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.