LeetCode 133: Clone Graph — Python Solution

LeetCode 133: Clone Graph is a Medium graph general problem. This Python walkthrough develops a DFS memoized cloning solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicGraph General
Reusable patternDFS memoized cloning
ComplexityO(V+E) time and O(V) space

Recognizing the pattern

Graph traversal separates reachability from representation: adjacency describes possible moves, while a visited structure prevents repeated work.

For this problem specifically, create and memoize a clone before recursively cloning neighbors, then attach cloned neighbor references. The invariant worth writing beside the code is: The map contains the unique clone for every discovered original node, preventing infinite recursion and duplicate clones.

Step-by-step algorithm

  1. Identify the input state consumed by cloneGraph(node) and initialize the data required by the DFS memoized cloning pattern.
  2. Create and memoize a clone before recursively cloning neighbors, then attach cloned neighbor references.
  3. After each update, verify the page’s central invariant: The map contains the unique clone for every discovered original node, preventing infinite recursion and duplicate clones.
  4. Finish only after the boundary behavior is covered: The graph may contain cycles, self-loops, or a single node.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

class Solution:
    def cloneGraph(self, node):
        copies = {}
        def clone(original):
            if not original: return None
            if original in copies: return copies[original]
            copy = Node(original.val)
            copies[original] = copy
            copy.neighbors = [clone(neighbor) for neighbor in original.neighbors]
            return copy
        return clone(node)

Reading the implementation

The main entry point is cloneGraph(node). The named working state includes copies, copy; those variables make the DFS memoized cloning state visible instead of hiding it in incidental control flow.

The method expresses the transformation directly without a general traversal loop. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, create and memoize a clone before recursively cloning neighbors, then attach cloned neighbor references.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Create and memoize a clone before recursively cloning neighbors, then attach cloned neighbor references. Each update records the current item without invalidating earlier decisions; consequently, the map contains the unique clone for every discovered original node, preventing infinite recursion and duplicate clones.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(V+E) time and O(V) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

DFS and BFS often have the same asymptotic cost; choose DFS for recursive structure and BFS when distance or processing order matters. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

g1,g2=Node(1),Node(2); g1.neighbors=[g2]; g2.neighbors=[g1]; clone=Solution().cloneGraph(g1); assert clone is not g1 and clone.neighbors[0].neighbors[0] is clone

Common mistakes and edge cases

  • Problem-specific boundary: The graph may contain cycles, self-loops, or a single node.
  • Pattern-level pitfall: Mark a state when it is discovered rather than after all of its neighbors are processed, or cycles can enqueue it repeatedly.
  • Invariant check: after every update, confirm that the map contains the unique clone for every discovered original node, preventing infinite recursion and duplicate clones.

Interview review checklist

  • Explain why DFS memoized cloning matches the structure of this input.
  • State the invariant in one sentence before tracing code: The map contains the unique clone for every discovered original node, preventing infinite recursion and duplicate clones.
  • Derive O(V+E) time and O(V) space from how many times each element or state is visited.
  • Test the boundary explicitly: The graph may contain cycles, self-loops, or a single node.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 130. Surrounded Regions · Next: 399. Evaluate Division