InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Clone Graph

medium Original ↗ 00:00

Problem

You are 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 graph: a new set of nodes with the same values and 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 difficulty is not visiting nodes; it is cloning each original node exactly once even though it is reachable along several paths in a cyclic graph.
Hint 2 Keep a hash map from original nodeits 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug