Clone a Directed Graph
Problem Statement#
Given the root node of a directed graph, clone this graph by creating its deep copy so that the cloned graph has the same vertices and edges as the original graph.
Let’s look at the graphs below as an example. If the input graph is G = (V, E) where V is set of vertices and E is set of edges, then the output graph (cloned graph) G’ = (V’, E’) such that V = V’ and E = E’.
Note: We are assuming that all vertices are reachable from the root vertex. i.e. we have a connected graph.
Solution#
Solution Explanation#
Runtime Complexity#
Linear, O(n).
Memory Complexity#
Logarithmic, O(n). ‘n’ is the number of vertices in the graph.
Solution Breakdown#
We use depth-first traversal and create a copy of each node while traversing the graph. To avoid getting stuck in cycles, we’ll use a hashtable to store each completed node and will not revisit nodes that exist in the hashtable. The hashtable key will be a node in the original graph, and its value will be the corresponding node in cloned graph.
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!