noodleProblems/
Clone Graph
#144

Clone Graph

AlgorithmmediumGraphDepth First SearchBreadth First SearchHash Table

Given a reference to a node in a **connected undirected graph**, return a **deep copy** (clone) of the graph. Each node holds an integer val and a list of its neighbors.

The graph is given in adjacency-list form: adjList[i] lists the neighbors of the node with value i + 1 (node values are the contiguous range 1..N, so the array is 0-indexed but values are 1-indexed). For example [[2,4],[1,3],[2,4],[1,3]] is a 4-node square: node 1 borders 2 and 4, node 2 borders 1 and 3, and so on. Your function receives the node with value 1.

Return the clone as the equivalent adjacency list.

**Grading note.** The tests serialize your returned graph and compare its *structure* to the expected adjacency list — they verify you rebuilt the right shape, but they cannot detect a solution that returns the *original* graph instead of a fresh copy (serialization erases object identity). Still write a genuine deep copy: allocate new nodes and wire new neighbor links.

Example cases

  • square
    in node =
    24
    13
    24
    13
    out [[2,4],[1,3],[2,4],[1,3]]
    A 4-cycle. The clone has the same four nodes and the same adjacency, rebuilt as new objects.
  • single node
    in node =
    out [[]]
    One node with no neighbors clones to one node with no neighbors.
  • empty graph
    in node = []
    out []

Constraints

  • The number of nodes is in the range [0, 100].
  • 1 <= Node.val <= 100, and Node.val is unique for each node.
  • There are no repeated edges and no self-loops.
  • The graph is connected, and all nodes can be reached from the given node.
Saved
node =
[[2,4],[1,3],[2,4],[1,3]]