v9.1.1
Menu

Clone Graph

mediumFREEGraphsBlind 75

Given an adjacency list representation of an undirected graph, create a deep copy (clone) of the graph.

Input: adj_list is a list with one entry per node: the kk-th entry (counting from 1) is the list of node kk's neighbour indices (nodes are 1-indexed). Return the cloned adjacency list in the same format: same neighbours in the same order, and fully independent of the input (modifying the clone must not change the original). An empty graph returns an empty list. The tests print each node's neighbours on one line, space-separated.

Example

Input
2,4
1,3
2,4
1,3
Output
2 4
1 3
2 4
1 3
Reasoning
  • Input: adj_list has one entry per node; the kk-th entry (counting from 1) lists the labels of node kk's neighbours. In the sample, nodes 1 and 3 each touch 2 and 4, while nodes 2 and 4 each touch 1 and 3.
  • The graph: the 4 edges 1–21\text{–}2, 2–32\text{–}3, 3–43\text{–}4, 4–14\text{–}1 form a 4-cycle. The graph is undirected, so each edge appears from both ends: 2×4=82 \times 4 = 8 entries.
  • Deep copy: the clone must describe exactly the same graph (same nodes, same neighbour labels, same order) but be fully independent of the original: adding node 3 to node 1's neighbours in the clone must leave the original's node 1 at {2,4}\{2, 4\}.
  • Output: the result prints as 2 4, 1 3, 2 4, 1 3, identical to the input line for line.
  • Edge case: a graph with no nodes clones to an empty result, which the tests print as EMPTY.

Constraints

  • 1 <= number of nodes <= 100
  • 0 <= neighbors per node <= nodes - 1
  • No self-loops or repeated edges

Learn this in

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.