View on NeetCode
View on LeetCode

Problem

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.

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: The input graph has one node with no neighbors.

Example 3:

Input: adjList = []
Output: []
Explanation: The graph is empty.

Constraints:

  • The number of nodes in the graph is in the range [0, 100].
  • 1 <= Node.val <= 100
  • Node.val is unique for each node.
  • There are no repeated edges and no self-loops in the graph.
  • The Graph is connected and all nodes can be visited starting from the given node.

Solution

Approach 1: DFS with HashMap

The key insight is to use a hashmap to track already cloned nodes, preventing infinite loops and ensuring each node is cloned exactly once.

Implementation

class Solution:
    def cloneGraph(self, node: 'Node') -> 'Node':
        if not node:
            return None

        # Map from original node to cloned node
        clones = {}

        def dfs(node):
            # If already cloned, return the clone
            if node in clones:
                return clones[node]

            # Create clone
            clone = Node(node.val)
            clones[node] = clone

            # Clone all neighbors
            for neighbor in node.neighbors:
                clone.neighbors.append(dfs(neighbor))

            return clone

        return dfs(node)

Approach 2: BFS with HashMap

from collections import deque

class Solution:
    def cloneGraph(self, node: 'Node') -> 'Node':
        if not node:
            return None

        clones = {node: Node(node.val)}
        queue = deque([node])

        while queue:
            curr = queue.popleft()

            for neighbor in curr.neighbors:
                if neighbor not in clones:
                    # Create clone for new neighbor
                    clones[neighbor] = Node(neighbor.val)
                    queue.append(neighbor)

                # Add cloned neighbor to current clone's neighbors
                clones[curr].neighbors.append(clones[neighbor])

        return clones[node]

Complexity Analysis

Both Approaches:

  • Time Complexity: O(N + E), where N is number of nodes and E is number of edges. We visit each node and edge once.
  • Space Complexity: O(N) for the hashmap storing cloned nodes.

Key Insights

  1. HashMap for Tracking: Essential to use a hashmap to map original nodes to cloned nodes, preventing infinite loops in cyclic graphs.

  2. Two-Phase Process: First create the node clone, then clone its neighbors. This allows handling cycles correctly.

  3. Deep Copy: We must create new node objects, not just copy references. Each node and its neighbor list must be new objects.

  4. Connected Graph: Since the graph is connected, starting from any node will reach all nodes via DFS/BFS.

  5. Handling Cycles: The hashmap check at the start of each recursive call/iteration prevents infinite loops from cycles.