We are required to clone a graph, where “cloning” implies a deep copy, creating an exact same graph with the same values, but none of the nodes can have the same memory as the original graph.
Like BSTs, graphs are recursive data structures. We can build them with a Depth-First approach or a Breadth-First approach. In the solution below, we are doing DFS.
The basic idea is very similar to other graph, matrices and trees problems.
Code:
Java
Big O Analysis
Runtime
The runtime complexity here is O(N) as since we would visit all nodes atleast once.
Memory
The memory usage is O(N) since we use a visited array. In this particular case, 1<=N<=100