Clone Graph
Problem Statement
You are given a reference to one node of a connected, undirected graph. Every node has an integer value and a list of neighbours.
Return a deep copy of the whole graph. Every node must be copied exactly once. The copy must have the same values and the same links as the original, but it must share no node with the original. Editing the copy must never change the input.
A reference node to one node of the graph, or null for an empty graph. Each node has val and a list neighbors.
A reference to the copy of node in the new graph, or null if the input is null.
Node 1 is linked to 2 and 4, node 2 to 1 and 3, node 3 to 2 and 4, and node 4 to 1 and 3. The copy has the same four links, on four new nodes.
A single node with no neighbours. The copy is one new node with an empty neighbour list.
- • The number of nodes is in the range [0, 100].
- • 1 ≤ Node.val ≤ 100
- • Node.val is unique for each node.
- • There are no repeated edges and no self-loops.
- • The graph is connected, and every node can be reached from the given node.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Collect all nodes in a list, make one copy per node, then find each neighbour's copy by a linear search
Create each copy the first time its node is seen; the map finds an existing copy in one lookup
First collect every original node in one list with a BFS. Make one new node for each entry. To link the copies, look at each neighbour of an original node and find its copy by scanning the list from the front, then add that copy to the matching copy's neighbour list.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.