Clone Graph

MediumGraphs

You get one node of a connected, undirected graph. Return a deep copy of the whole graph: new nodes with the same values and the same connections, sharing no node with the original.

Each node has a val and a list of neighbors. Values run from 1 to n, one per node. On this page a graph is written as an adjacency list: position i lists the neighbors of the node with value i + 1, and the node you get is the one with value 1.

Examples

Example 1
Input:  node = [[2, 3], [1, 3], [1, 2]]
Output: [[2, 3], [1, 3], [1, 2]]

A triangle: each node links to the other two, and so must each copy.

Example 2
Input:  node = [[]]
Output: [[]]

One node with no neighbors.

Constraints

  • The graph has 0 to 100 nodes.
  • Each value from 1 to n is used once.
  • No edge repeats, and no node links to itself.

Stuck?

Hint 1

Keep a Map from each original node to its copy, so a node you reach twice is copied once.

Hint 2

Walk the graph with DFS or BFS. Make a node’s copy the first time you see it, then fill in its neighbors from the Map.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 8 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur