Search⌘ K
AI Features

Solution: Clone Graph

Explore how to clone an undirected connected graph using depth-first search and a hash map. Understand the recursive approach to create new node instances and handle neighbors while avoiding revisiting nodes. This lesson helps you implement a graph deep-copy solution with O(n + m) time complexity and grasp key graph traversal strategies.

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 the given 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.

Each node in the graph contains two properties:

  • data: The value of the node, which is the same as its index in the adjacency list.

  • neighbors: A list of connected nodes, representing all the nodes directly linked to this node.

However, in the test cases, a graph is represented as an adjacency list to understand node relationships, where each index in the list represents a node (using 1-based indexing). For example, for ...