0:00 / 0:00

Deep-copy a whole graph from one node. Walk it with depth-first search, and keep a map from each original to its copy so cycles are cloned once.

▼

The problem

LeetCode 133 (Medium). Given a reference to one node of a connected, undirected graph (each node has a val and a list of neighbors), return a deep copy: new nodes with the same values, wired the same way, sharing nothing with the original.

Example (LeetCode's): adjacency [[2,4],[1,3],[2,4],[1,3]], a four-node loop 1-2-3-4-1. Plain recursion with no memory goes 1 → 2 → 1 → 2 … forever.

def cloneGraph(node):
    copies = {}                    # original -> copy
    def clone(n):
        if n in copies:
            return copies[n]       # reuse
        copy = Node(n.val)
        copies[n] = copy           # store first
        for nb in n.neighbors:
            copy.neighbors.append(clone(nb))
        return copy
    return clone(node) if node else None
TRY IT ON LEETCODE ▶

The solution

def cloneGraph(node):
    copies = {}                    # original -> copy
    def clone(n):
        if n in copies:
            return copies[n]       # reuse
        copy = Node(n.val)
        copies[n] = copy           # store first
        for nb in n.neighbors:
            copy.neighbors.append(clone(nb))
        return copy
    return clone(node) if node else None

Transcript

Clone Graph. You're handed one node of a connected, undirected graph. Each node holds a value and a list of its neighbors. Return a deep copy: brand new nodes with the same values, wired the same way, sharing nothing with the original.

Take four nodes in a loop. One is joined to two and four, and three is joined to two and four. The copy needs four new nodes and the same four edges, and every edge runs both ways.

The obvious plan is recursion: to copy a node, make a new one, then copy each neighbor the same way. But the graph has a cycle. One copies two, two copies one again, which copies two again, and it never stops.

The fix is memory: a hash map from each original node to its copy. Before copying a node, look it up. If it's there, reuse that copy. If not, make one and store it right away, before visiting any neighbors. That early store breaks the cycle.

In code, a helper takes a node. If it's in the map, return its copy. Otherwise, create a node with the same value and store it. Then append the clone of each neighbor to its list, and return the copy.

Let's run it from one. One isn't in the map: new copy, stored. Its neighbor two: new copy. Two looks back at one, already in the map, so it reuses it. Then three: new copy, and it sees two: reuse. Then four: new copy, and it sees one and three: both reused. The calls return, and one finally looks at four, already stored. Four copies, five reuses, every edge rebuilt.

Each node is copied once, and each edge is looked at from both ends, so the time is big O of V plus E. The map holds one copy per node, and the recursion can go V deep, so the space is big O of V.

Copy each node once, remember it, reuse it. That's Clone Graph.