/133. Clone Undirected Graph

133. Clone Undirected Graph

Medium
Hash Table64.8% acceptance

Given an undirected connected graph represented as an adjacency list, where each node has a unique integer identifier starting from 1, construct a deep copy of the graph. The input is a list of lists, where the i-th list contains the identifiers of the neighbors of node i+1. Return the adjacency list representation of the cloned graph, starting from the node with identifier 1. If the input graph is empty, return an empty list.

Example 1

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

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

Explanation: There are 3 nodes. Node 1 connects to 3, Node 2 connects to 3, Node 3 connects to 1 and 2.

Example 2

Input: [[]]

Output: [[]]

Explanation: Single node with no neighbors.

Example 3

Input: []

Output: []

Explanation: Empty graph.

Example 4

Input: [[2],[1]]

Output: [[2],[1]]

Explanation: Two nodes, each connected to the other.

Constraints

  • 0 <= number of nodes <= 100
  • 1 <= node identifier <= 100
  • Each node identifier is unique
  • No repeated edges
  • No self-loops
  • Graph is connected and all nodes are reachable from node 1
Python (current runtime)

Case 1

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

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

Case 2

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

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

Case 3

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

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