...

/

Clone Graph

Clone Graph

Try to solve the Clone Graph problem.

Statement

You are given a reference to a single node in an undirected, connected graph. Your task is to create a deep copy of the graph starting from this node. A deep copy means creating a new instance of every node in the graph with the same data and edges as the original graph, such that changes in the copied graph do not affect the original graph.

From the programming perspective, the graph is represented as an adjacency list to understand node relationships. Each node in the adjacency list corresponds to a node in the graph, and the list of neighbors describes that node’s connections. For example, for [[2,3],[1,3],[1,2]][[2, 3], [1, 3], [1, 2]], there are three nodes in the graph:

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

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

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

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

Press + to interact
canvasAnimation-image
1 / 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.

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

1
2
3
4
5

Try it yourself

Implement your solution in CloneGraph.java in the following coding playground.

Press + to interact
Java
usercode > CloneGraph.java
import java.util.*;
public class CloneGraph{
public static Node clone(Node root) {
// Replace this placeholder return statement with your code
return root;
}
}
Clone Graph

Access this course and 1200+ top-rated courses and projects.