Practice/LinkedIn/Leetcode 133. Clone Graph
CodingMust
You are given a reference to a node in a connected undirected graph. Your task is to create and return a deep copy of the entire graph.
Each node in the graph contains an integer value and a list of its neighboring nodes. The graph is represented using an adjacency list where each node holds references to all nodes directly connected to it.
Your cloned graph must be completely independent of the original — modifying the clone should not affect the original graph in any way. Every node in the original graph must map to exactly one unique node in the cloned graph, preserving all structural relationships including cycles and shared neighbors.
Example 1:
Input: Node 1 with no neighbors Output: A new Node with value 1 and empty neighbors list Explanation: A single isolated node is cloned with the same value and no connections.
Example 2:
Input: Node 1 connected to Node 2 (bidirectional) Adjacency list: \{\{1, [2]\}, \{2, [1]\}\} Output: Cloned Node 1 connected to cloned Node 2 Explanation: The two nodes and their mutual connection are preserved in the clone.
Example 3:
Input: Four nodes in a square formation Node 1 connects to [2, 4] Node 2 connects to [1, 3] Node 3 connects to [2, 4] Node 4 connects to [1, 3] Output: A cloned graph maintaining the same square structure Explanation: All four nodes and their connections form an identical but independent copy.
Example 4:
Input: null Output: null Explanation: An empty graph input should return null.