Clone Graph

Try to solve the Clone Graph problem.

Statement#

Given a graph that has nodes with data and a list of neighbors, create a deep copy of the graph. The graph has the following properties:

  • Undirected: The edges of the graph are bidirectional.

  • Connected: A path will always exist between any two nodes.

In a deep copy, a new instance of every node is created with the same data as in the original graph. Any modifications made to the new graph are not reflected in the original graph.

For simplicity, we are creating a graph using an adjacency list, where the data of each node is represented by its index in the adjacency list. Each list in the adjacency list describes the set of neighbors of a node in the graph. The index in the adjacency list starts from 1. For example, for [[2, 3], [1, 3], [1, 2]], there are three nodes in the graph:

1st1^{st} node (data = 1): Neighbors are 2nd2^{nd} node (data = 2) and 3rd3^{rd} node (data = 3).

2nd2^{nd} node (data = 2): Neighbors are 1st1^{st} node (data = 1) and 3rd3^{rd} node (data = 3).

3rd3^{rd} node (data = 3): Neighbors are 1st1^{st} node (data = 1) and 2nd2^{nd} node (data = 2).

Constraints:

  • 00 \leq Number of nodes 100\leq 100
  • 11 \leq Node.data 100\leq 100
  • Node.data is unique for each node.
  • The graph is undirected, i.e., there are no self-loops or repeated edges.
  • The graph is connected, i.e., any node can be visited from a given node.

Examples#

canvasAnimation-image

1 of 3

canvasAnimation-image

2 of 3

canvasAnimation-image

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:

Clone Graph

1

Which graph is made from the given adjacency list?

[[2, 5], [1, 3], [2, 4], [3, 5], [1, 4]]

A)
3-------1|        \|         2|         /5--------4
B)
1-------5|        \|         3|         /2--------4
C)
1-------2|        \|         3|         /5--------4
D)
1-------2|        \|         5|         /3--------4
Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Create a new Node with the same data as the root of the original graph.

Add the root node and its clone to a hash map.

Iterate through the neighbors of the root node.

If the neighbor is not cloned yet, recursively clone it. If the neighbor is already cloned, add it to the new node’s neighbors.

Return the root of the new graph.


Try it yourself#

Implement your solution in clone_graph.py in the following coding playground. We have provided a useful code template in the other file that you may build on to solve this problem.

Python
clone_graph.py
Node.py
Input #1
Clone Graph

Graphs: Introduction

Solution: Clone Graph