Problems/Graphs/Graph Deep Copy
Graphs
medium

Graph Deep Copy

The problem is to create a completely independent copy of a graph given a starting node. This tests your understanding of graph traversal and deep copying techniques, crucial for many real-world applications like data structure manipulation and algorithm design.

graphdfsrecursiondeep copymemoization

Problem Statement

Given the reference to a node within a connected, undirected graph, construct and return a deep copy of the entire graph. The copied graph should have identical structure and node values as the original, but all nodes in the new graph must be newly created instances, with no shared references to the original graph's nodes.

Example 1
Input: Original Graph: Node 1 -> Node 2, Node 2 -> Node 1, Node 2 -> Node 3, Node 3 -> Node 2
Output: Cloned Graph: Node 1' -> Node 2', Node 2' -> Node 1', Node 2' -> Node 3', Node 3' -> Node 2'
The cloned graph mirrors the original. Node 1' in the cloned graph is a new instance, pointing to a new instance Node 2'. Similarly, Node 2' points to Node 1' and Node 3', and Node 3' points to Node 2'.
Example 2
Input: Original Graph: Node 5 -> Node 6, Node 5 -> Node 7, Node 6 -> Node 5, Node 7 -> Node 5
Output: Cloned Graph: Node 5' -> Node 6', Node 5' -> Node 7', Node 6' -> Node 5', Node 7' -> Node 5'
Even with different node values, the cloned graph maintains the same connections as the original. Node 5' (value 5) is a distinct copy connected to distinct copies of Node 6' and Node 7'.
Constraints
  • -The graph is undirected.
  • -Each node has a unique value.
  • -The input node is reachable from every node in the graph.
  • -The number of nodes in the graph is between 1 and 100.
  • -Node values are integers between 1 and 100.

Brute Force Approach

A brute-force approach would involve visiting each node in the original graph and creating a new node with the same value in the cloned graph. You'd then iterate through the neighbors of each original node, find their corresponding clones, and establish the same connections in the cloned graph. This is like manually recreating a social network profile by profile, connection by connection. The time complexity would be proportional to the number of nodes and edges, and the space complexity would depend on the size of the cloned graph.

TimeO(n + e)
SpaceO(n)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem