Medium · Graphs

Clone Graph

Given node 0 of an undirected graph built from adjacency lists adj (node i has label i and neighbors adj[i] in that order), return a deep copy of every node reachable from it with the same labels and neighbor order, sharing no node with the original; return null when the graph is empty.

Examples

Example 1

{
  "adj": [
    [1, 2],
    [0, 2, 3],
    [0, 1, 4],
    [1, 4],
    [2, 3]
  ],
  "pos": [
    [176, 44],
    [270, 112],
    [234, 223],
    [118, 223],
    [82, 112]
  ]
}

Output: 5 cloned

Example 2

{
  "adj": [
    [1, 3],
    [0, 2],
    [1, 3],
    [0, 2]
  ],
  "pos": [
    [176, 44],
    [275, 143],
    [176, 242],
    [77, 143]
  ]
}

Output: 4 cloned

Rebuild it in the studio

Read every interview problem free. Ten rooms need no account. A token opens a problem in full — Pro never counts.

More Graphs problems