TRT
Sign in
mediumAdvancedLeetCode#traversal with an old-to-new map

Clone graph

Deep-copy a connected undirected graph, mapping each original vertex to its copy so that cycles are copied once.

The Runtime Theory Team1 min read
Taught inRepresenting graphsPro — members onlyA graph is a set of vertices joined by edges. How you store it, as adjacency lists, an adjacency matrix or an edge list, decides the cost of every algorithm you run on it.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inadjList = [[2, 4], [1, 3], [2, 4], [1, 3]]

outan equal graph made of new nodes

inadjList = [[]]

out[[]]

inadjList = []

out[]

Given a reference to a vertex of a connected undirected graph, where each vertex has a value and a list of neighbors, return a deep copy of the graph.

Before you code

A graph has cycles, so a naive recursive copy would loop forever. The map from original vertex to copy doubles as the visited set.

Hints

  1. Keep copies = {original: clone}.
  2. Traverse with BFS or DFS. When you meet a neighbor with no copy yet, create it and schedule it for processing.
  3. Append the neighbor's copy to the current clone's neighbor list.

Production & complexity notes

When solving Clone graph on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Representing graphs to reinforce the underlying pattern.

What it practices

Walking adjacency lists with a visited map, from Representing graphs.

Not started

Sign in to save your learning progress.

Sign in to save