Skip to main content
43

Clone Graph

Mediumgraphsdfshash map

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:GraphsRead the beginner guide

You're given a reference to one node of a connected, undirected graph. Return a deep copy (clone) of the whole graph.

Each node has a val and a list of neighbors:

text
class GraphNode { val: number; neighbors: GraphNode[] }

Understand the problem

  • A graph is a set of nodes where any node can be connected to any other (unlike a tree, there's no root and no parent/child). Undirected means connections go both ways: if 1 lists 2 as a neighbor, 2 lists 1.
  • Connected means every node can be reached from the one you're given.
  • A deep copy means brand-new node objects, with the same values and the same connections, but none of them may be an original node. Changing the copy must not affect the original.

Example 1

text
Input:  [[2, 4], [1, 3], [2, 4], [1, 3]]

  1 ── 2
  │    │
  4 ── 3

Output: [[2, 4], [1, 3], [2, 4], [1, 3]]

Four nodes in a square. The copy has the same shape, made of new nodes.

Example 2

text
Input:  [[]]
Output: [[]]

One node with no neighbors.

Example 3

text
Input:  []
Output: []

An empty graph: you receive null and return null.

How the tests work: a graph is written as an adjacency list: entry i lists the neighbors of the node with value i + 1. The node passed to your function is the one with value 1.

Constraints

  • 0 <= number of nodes <= 100
  • Node values are 1..n, unique; no repeated edges or self-loops.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Copy nodes recursively, using a map from each original node to its copy, so every node is copied exactly once and cycles don't loop forever.

    The difficulty: cycles

    Copying a tree is easy: copy the node, then recursively copy its children. A graph can have cycles:

    text
    1 → neighbor 2 → neighbor 1 → neighbor 2 → ...

    A naive recursion follows this forever. And even in a graph without loops, two nodes can share a neighbor, and you'd copy that neighbor twice, which breaks the shape.

    The key insight

    Keep a map copies from each original node to its copy. It does two jobs at once:

    1. It's the "visited" set: if a node is already in the map, we've handled it.
    2. It gives you the one copy of each node, so all references point to the same new node.

    clone(node):

    1. If node is already in copies, return its copy. (Stops cycles, avoids duplicates.)
    2. Create the copy with the same value, and put it in the map right away, before touching the neighbors.
    3. Set the copy's neighbors to clone(neighbor) for each original neighbor.

    Step 2's order is the important detail: when the recursion comes back around to this node through a cycle, it must find the copy already in the map.

    Step by step

    The square 1 ── 2 ── 3 ── 4 ── 1:

    CallIn the map?What happens
    clone(1)nocreate 1', map it; clone neighbors 2, 4
    clone(2)nocreate 2', map it; clone neighbors 1, 3
    clone(1)yesreturn 1' (the cycle stops here)
    clone(3)nocreate 3', map it; clone neighbors 2, 4
    clone(2)yesreturn 2'
    clone(4)nocreate 4', map it; clone neighbors 1, 3: both in the map
    back up3'.neighbors = [2', 4'], 2'.neighbors = [1', 3']
    clone(4)yes(from 1's list) return 4'; 1'.neighbors = [2', 4']

    Every node was created once, and the copies are wired exactly like the originals.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With V nodes and E edges:

    • Time: O(V + E). Each node is copied once, and each edge is followed once from each side.
    • Memory: O(V) for the map and the recursion.

    Common mistakes

    • Adding to the map after cloning the neighbors. Then the cycle never sees the copy, and the recursion loops forever.
    • Returning the original node somewhere (for example, copying the neighbors list as-is). The copy must contain only new nodes.
    • Using values as map keys instead of the nodes. Works here because values are unique, but it's a habit that breaks on graphs with repeated values.

    Going deeper

    • BFS works too: create the copy of the start node, then use a queue. For each node you pop, look at its neighbors: create (and queue) any copy that doesn't exist yet, and add it to the current copy's neighbors.
    • "A map from old to new" is the standard way to copy any structure with shared or circular references, like a linked list with random pointers.

    Reference solution

    js
    /**
     * @param {GraphNode | null} node
     * @return {GraphNode | null}
     */
    export default function cloneGraph(node) {
      // original node → its copy. Doubles as the "visited" set.
      const copies = new Map()
    
      function clone(original) {
        // Already copied (we came back around a cycle): reuse the one copy.
        if (copies.has(original)) return copies.get(original)
        const copy = new GraphNode(original.val)
        // Register the copy BEFORE cloning neighbors, so a cycle back to here finds it.
        copies.set(original, copy)
        copy.neighbors = original.neighbors.map(clone)
        return copy
      }
    
      return node ? clone(node) : null
    }
    ts
    export default function cloneGraph(node: GraphNode | null): GraphNode | null {
      // original node → its copy. Doubles as the "visited" set.
      const copies = new Map<GraphNode, GraphNode>()
    
      function clone(original: GraphNode): GraphNode {
        // Already copied (we came back around a cycle): reuse the one copy.
        const existing = copies.get(original)
        if (existing) return existing
        const copy = new GraphNode(original.val)
        // Register the copy BEFORE cloning neighbors, so a cycle back to here finds it.
        copies.set(original, copy)
        copy.neighbors = original.neighbors.map(clone)
        return copy
      }
    
      return node ? clone(node) : null
    }
    python
    def clone_graph(node: GraphNode | None) -> GraphNode | None:
        # original node → its copy. Doubles as the "visited" set.
        copies = {}
    
        def clone(original: GraphNode) -> GraphNode:
            # Already copied (we came back around a cycle): reuse the one copy.
            if original in copies:
                return copies[original]
            copy = GraphNode(original.val)
            # Register the copy BEFORE cloning neighbors, so a cycle back to here finds it.
            copies[original] = copy
            copy.neighbors = [clone(n) for n in original.neighbors]
            return copy
    
        return clone(node) if node else None