DIY: Clone Undirected Graph
Solve the interview question "Clone Undirected Graph" in this lesson.
We'll cover the following
Problem statement
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. The graph is represented using an adjacency list.
Each node in the graph contains a data
(int) and a neighbors
(std::vector[Node *] of its neighbors).
class Node {
int data;
std::vector<Node*> neighbors;
}
Input
The input graph will be in the form of an adjacency list. The following is an example input:
G = [[2,4],[1,3],[2,4],[1,3]]
Output
The output will be a deep copy of the input graph, and it will be in the form of an adjacency list. The following is an example output:
G` = [[2,4],[1,3],[2,4],[1,3]]
Coding exercise
Implement the clone(rootNode)
function, where rootNode
is the input’s graph starting node through which the rest of the graph can be traversed. The function returns the root node of the cloned graph.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.