MediumDepth-First SearchBreadth-First SearchGraphHash TableUpdated Sep 2026

133. Clone Graph

Asked at Google, Meta, Amazon, Microsoft and 1 more

Difficulty

Medium

Time

O(V + E)

Space

O(V)

Pattern

Depth-First Search

Companies

5

Problem

You are given a reference to one node in a connected undirected graph. Every node holds an integer val and a list of neighbors. Your job is to return a deep copy of the whole graph: brand new node objects with the same values and the same connections.

The returned node must be the clone of the node you were given. The clone must not share any node object with the original graph — copying only the values is not enough, you must copy the links too.

The graph is connected, so starting from the given node you can reach every other node. Nodes have unique values, there are no self-loops and no repeated edges. The input is written as an adjacency list: the i-th inner list holds the values of the neighbors of the node with value i+1. The given node always has val = 1.

A hash map from original node to its clone is the key trick. It plays two roles: it tells you which nodes you have already copied, and it gives you the clone to attach when a neighbor points back to a node you have seen before. Without it, cycles in the graph would send you into an infinite loop.

Copy the graph, not just the values

adjListneighbors12341: [2,4]2: [1,3]3: [2,4]4: [1,3]Each row lists the neighbors of that node value.input: original nodes 1-2-3-4 cycleoutput: new nodes, same cycleThe clone must be a brand new graph, not a pointer tothe old one.
The input is a 4-node cycle. The output must be a separate set of nodes with the same shape.

Constraints

  • ●The number of nodes in the graph is in the range [0, 100].
  • ●1 <= Node.val <= 100
  • ●Node.val is unique for each node.
  • ●There are no repeated edges and no self-loops in the graph.
  • ●The graph is connected and all nodes can be visited starting from the given node.

Examples

Example 1
InputadjList = [[2,4],[1,3],[2,4],[1,3]]
Output[[2,4],[1,3],[2,4],[1,3]]
WhyFour nodes form a cycle: 1 links to 2 and 4, 2 links to 1 and 3, 3 links to 2 and 4, 4 links to 1 and 3. The clone must have the same four nodes and the same four connections, but with new node objects.
Example 2
InputadjList = [[]]
Output[[]]
WhyThere is only one node, value 1, and it has no neighbors. The clone is a single new node with an empty neighbor list.
Example 3
InputadjList = []
Output[]
WhyThe graph has no nodes at all, so the given reference is null and we return null.

Asked At

5 companies

How to Think About It

1

Use a hash map to map original nodes to their clones. This prevents infinite loops and duplicate work.

2

DFS: for each node, if not yet cloned, create a clone, add to map, then recursively clone all neighbors. Attach cloned neighbors to the cloned node.

3

BFS alternative: same idea but use a queue. Enqueue the original node, clone it, then enqueue unvisited neighbors.

4

The hash map serves as both the visited set and the mapping. If a node is already in the map, return its clone immediately.

5

Edge cases: single node with no neighbors, self-loop, disconnected components (not possible per problem statement).

Optimal Approach

Step 1: If node is null, return null.
Step 2: Create hash mapcloned = {original: clone}.
Step 3: DFS function: if node in cloned, return cloned[node]. Create new node, add to map. For each neighbor, recursively clone and attach.
Step 4: Return cloned[node].

Time: O(V + E) — visit every node and edge once. Space: O(V) — hash map and recursion stack.

DFS with a map from original to clone

clonedcloneorigorigorigorig1 -> clone12 -> clone23 -> clone34 -> clone4After visiting 1 and 2, the map already holds theirclones.clone 1, map[1]=c1neighbor 2: clone 2, map[2]=c2neighbor 1: already in map, reuse c1neighbor 3: clone 3, then 4When a neighbor is already in the map, we attach thestored clone instead of recursing again.if n in cloned: return cloned[n]copy = Node(n.val); cloned[n] = copyfor nb in n.neighbors: copy.neighbors.append(dfs(nb))
The map stops the recursion when a node is reached a second time through a cycle.
ComplexityTime O(V + E)Space O(V)Each node and each edge is handled once; the hash map and the recursion stack each hold at most V entries.

What Trips People Up in Real Interviews

1

Not using a visited map. Without it, you'll get infinite loops on cyclic graphs.

2

Confusing "deep copy" with "shallow copy." A deep copy means the cloned graph has no references to the original graph's nodes.

3

Not handling null input. If the reference node is null, return null.

4

Forgetting to clone all neighbors. After cloning a node, recursively clone all its neighbors and attach them.

5

Using BFS instead of DFS. Both work, but DFS is more natural for recursive graph cloning and uses less explicit state. BFS requires a queue and more bookkeeping.

Solution Code

O(V + E) time
class Node:
    def __init__(self, val=0, neighbors=None):
        self.val = val
        self.neighbors = neighbors or []

def cloneGraph(node):
    if not node:
        return None
    cloned = {}
    def dfs(n):
        if n in cloned:
            return cloned[n]
        copy = Node(n.val)
        cloned[n] = copy
        for neighbor in n.neighbors:
            copy.neighbors.append(dfs(neighbor))
        return copy
    return dfs(node)

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Clone Graph problem?

Given a reference of a node in a connected undirected graph, return a deep copy of the graph. Each node contains a value and a list of its neighbors.

How do you solve Clone Graph?

The optimal approach runs in O(V + E) time and O(V) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Clone Graph?

Clone Graph is asked at Google, Meta, Amazon, Microsoft, Uber. It is a medium difficulty problem.

What are common mistakes on Clone Graph?
  • Not using a visited map. Without it, you'll get infinite loops on cyclic graphs.
  • Confusing "deep copy" with "shallow copy." A deep copy means the cloned graph has no references to the original graph's nodes.
  • Not handling `null` input. If the reference node is `null`, return `null`.
  • Forgetting to clone all neighbors. After cloning a node, recursively clone all its neighbors and attach them.
  • Using BFS instead of DFS. Both work, but DFS is more natural for recursive graph cloning and uses less explicit state. BFS requires a queue and more bookkeeping.