Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
Example 1:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]] Output: [[2,4],[1,3],[2,4],[1,3]] Explanation: There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
Example 2:
Input: adjList = [[]] Output: [[]] Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
Example 3:
Input: adjList = [] Output: [] Explanation: This an empty graph, it does not have any nodes.
Constraints:
[0, 100].1 <= Node.val <= 100Node.val is unique for each node.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are trying to make an exact copy of a complex web of connected dots and lines from scratch. The brute force approach involves blindly recreating every single connection by repeatedly exploring the entire network over and over again for every piece you need to duplicate.
Here's how the algorithm would work step-by-step:
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
def clone_graph_brute_force(original_node):
if original_node is None:
return None
# We use a lookup dictionary to track visited nodes and prevent infinite loops in cyclic graphs
visited_mapping = {}
def recursive_clone(current_node):
if current_node in visited_mapping:
return visited_mapping[current_node]
duplicated_node = Node(current_node.val)
visited_mapping[current_node] = duplicated_node
# We iterate through all neighbors to mirror the exact topological structure of the original graph
for neighbor_node in current_node.neighbors:
duplicated_node.neighbors.append(recursive_clone(neighbor_node))
return duplicated_node
# We initiate the deep copy process from the starting node to traverse the entire connected component
return recursive_clone(original_node)To create an exact duplicate of a connected network of nodes, we can explore the network step by step while keeping a handy registry of every new clone we make. This ensures that even if we visit the same part of the network multiple times or encounter loops, we never accidentally create duplicate copies or get stuck in an infinite cycle.
Here's how the algorithm would work step-by-step:
def clone_graph(original_node):
if not original_node:
return None
# A registry prevents infinite loops in cyclic graphs and duplicate node creations.
visited_nodes_map = {}
def depth_first_search(current_node):
if current_node in visited_nodes_map:
return visited_nodes_map[current_node]
# Creating a twin copy immediately ensures we can reference it for graph cycles.
cloned_node = Node(current_node.val)
visited_nodes_map[current_node] = cloned_node
for neighbor_node in current_node.neighbors:
cloned_node.neighbors.append(depth_first_search(neighbor_node))
return cloned_node
# We initiate the recursive deep copy starting from the provided source node.
return depth_first_search(original_node)| Case | How to Handle |
|---|---|
| Null input node | Check if the input node is null at the very beginning and return null immediately. |
| Graph with a single node and no neighbors | Create a new clone of the node, store it in the visited map, and return it without entering any neighbor loops. |
| Graph containing cycles such as a triangle or self-loop | Use a hash map to track visited original nodes and their clones to prevent infinite recursion and correctly wire back-edges. |
| Nodes with identical integer values throughout the graph | Store references to the actual node objects, rather than their values, as keys in the visited hash map to differentiate them. |
| Deeply skewed or linear graphs resembling a linked list | Iterative breadth-first search or memoized depth-first search should be used to avoid stack overflow issues in languages with strict recursion limits. |
| Disconnected components or unreachable nodes | Since the problem specifies a connected undirected graph, we only need to traverse starting from the given reference node. |