LeetCode 133: Clone Graph — Python Solution

Solve LeetCode 133: Clone Graph in Python with a DFS memoized cloning approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

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

What the problem is testing

Create and memoize a clone before recursively cloning neighbors, then attach cloned neighbor references.

Algorithm

  1. Create and memoize a clone before recursively cloning neighbors, then attach cloned neighbor references.
  2. Maintain this invariant: The map contains the unique clone for every discovered original node, preventing infinite recursion and duplicate clones.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

LeetCode provides the list, tree, or graph node definition used by the method.

from collections import Counter, defaultdict, deque, OrderedDict
import random

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)

Why this is correct

The proof follows the maintained state: The map contains the unique clone for every discovered original node, preventing infinite recursion and duplicate clones. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

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

Edge cases

The graph may contain cycles, self-loops, or a single node.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


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