/133. Clone Graph

133. Clone Graph

Medium
Hash Table64.8% acceptance

Given a reference to a node in a connected undirected graph, where each node contains an integer value and a list of its neighboring nodes, return a deep copy (clone) of the graph. The graph is represented as an adjacency list, where each node's value is unique and corresponds to its index (1-indexed). The input node is always the node with value 1. Return the reference to the cloned node corresponding to the input node. The output should be an adjacency list representing the cloned graph, using the same node value conventions.

Example 1

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

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

Explanation: There are 3 nodes. Node 1s neighbor is 2. Node 2s neighbors are 1 and 3. Node 3's neighbor is 2.

Example 2

Input: adjList = [[]]

Output: [[]]

Explanation: Single node with no neighbors.

Example 3

Input: adjList = []

Output: []

Explanation: Empty graph.

Example 4

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

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

Explanation: Triangle graph with 3 nodes.

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.
Python (current runtime)

Case 1

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

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

Case 2

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

Expected: [[2],[1]]