Clone Graph

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.

Each node in the graph contains a value (val) and a list of its neighbors.

`

class Node {

val: number

neighbors: Node[]

}

`

The graph is represented as an adjacency list where adjList[i] lists the neighbors of node i + 1. Node values are 1-indexed.

Your function receives the graph as an adjacency list and must return a deep copy — modifying the clone should not affect the original.

Examples

Example 1:

Input: adjList = [[2,4],[1,3],[2,4],[1,3]]

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

Explanation: There are 4 nodes. Node 1 connects to 2 and 4. Node 2 connects to 1 and 3. Node 3 connects to 2 and 4. Node 4 connects to 1 and 3. The cloned graph has the same structure.

Example 2:

Input: adjList = [[]]

Output: [[]]

Explanation: A single node with no neighbors. The clone is also a single node with no neighbors.

Example 3:

Input: adjList = [[2],[1]]

Output: [[2],[1]]

Explanation: Two nodes connected to each other.

Constraints

  • The number of nodes in the graph 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 in the graph
  • The graph is connected and all nodes can be visited starting from the given node
Source: Graphs pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle