SDE & MLE Prep

133. Clone Graph

Problem

Given a reference to one node of a connected undirected graph, where each node has a val and a list of neighbors, return a deep copy of the whole graph.

Example: the 4-cycle 1–2–3–4–1 → an identical, independent 4-cycle

Constraints: up to 100 nodes; values are unique.

DFS with a map original → clone. Create the clone before recursing into neighbours so cycles resolve through the map.

Complexity: O(V + E).

class Node:  # provided by LeetCode
    def __init__(self, val=0, neighbors=None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []

class Solution:
    def cloneGraph(self, node: Optional["Node"]) -> Optional["Node"]:
        clones = {}

        def dfs(n):
            if n in clones:
                return clones[n]
            c = clones[n] = Node(n.val)
            c.neighbors = [dfs(nb) for nb in n.neighbors]
            return c

        return dfs(node) if node else None