Blind 75
43 / 75Free practice

Clone Graph

Medium · Graphs

Jump to code

Deep-copy the connected component reachable from a graph node. Each node has a value and a list of neighboring nodes; cycles may occur. Return null for a null input.

Examples

Example 1

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

Output: [[2,4],[1,3],[2,4],[1,3]]

Example 2

node = [[]]

Output: [[]]

Constraints

  • 0 <= The number of nodes in the graph <= 100.
  • 1 <= Node.val <= 100
  • There are no duplicate edges and no self-loops in the graph.

Function contract

The input is an adjacency list of a connected graph. Node values are 1-based row numbers. The grader constructs Node objects and verifies the returned graph is a deep copy with the same edges.

Need a hint?

Remember clones by original node identity before traversing edges.

Asked in real interviews

Candidates reported versions of Clone Graph from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      2,
      4
    ],
    [
      1,
      3
    ],
    [
      2,
      4
    ],
    [
      1,
      3
    ]
  ]
]
Expected
[
  [
    2,
    4
  ],
  [
    1,
    3
  ],
  [
    2,
    4
  ],
  [
    1,
    3
  ]
]
Case 2
Input
[
  [
    []
  ]
]
Expected
[
  []
]
Case 3
Input
[
  []
]
Expected
[]
Case 4
Input
[
  [
    [
      2
    ],
    [
      1
    ]
  ]
]
Expected
[
  [
    2
  ],
  [
    1
  ]
]
Case 5
Input
[
  [
    [
      2
    ],
    [
      1,
      3
    ],
    [
      2
    ]
  ]
]
Expected
[
  [
    2
  ],
  [
    1,
    3
  ],
  [
    2
  ]
]

Drafts are saved per language in this browser when storage is available.