Talentd
FleetCode
Make and follow sheets.Sign in

Clone Graph solution and explanation

MediumBreadth-First SearchDepth-First SearchGraphHash Table8 min read66.1% acceptanceUpdated 9 Apr 2026
Clone Graph - Depth First Search - Leetcode 133NeetCode · 11:48 · 355K viewsWatch on YouTube
9 more videos on this problem
  1. Clone Graph - Depth First Search - Leetcode 133NeetCode · 11:48 · 355K views
  2. Clone graph | Leetcode #133Techdose · 13:01 · 63K views
  3. 9. Clone Graph | Tricky Question | LeetCode 133 | Explained with Intuition - Simple C++, JAVA codeKeerti Purswani · 22:11 · 19K views
  4. Clone Graph - Leetcode 133 - Graphs (Python)Greg Hogg · 13:38 · 17K views
  5. LeetCode #133: Clone Graph | Facebook Coding Interview | Amazon Coding InterviewKnowledge Center · 16:36 · 12K views
  6. CLONE GRAPH | LEETCODE # 133 | PYTHON BFS SOLUTIONCracking FAANG · 9:28 · 5K views
  7. [Java] Leetcode 133. Clone Graph [Search #7]Eric Programming · 12:56 · 4K views
  8. Clone Graph - LeetCode 133 - Python #blind75 #leetcode #clonegraphDeepti Talesra · 16:59 · 3K views
  9. Clone Graph - LeetCode 133 - JavaScriptAlgoJS · 9:22 · 2K views
  10. How to clone a graph (LeetCode #133) - Inside codeInside code · 6:12 · 2K views

The problem

Given a reference of a node in a connected undirected graph.

Return a deep copy (clone) of the graph.

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

class Node {
    public int val;
    public List<Node> neighbors;
}

Test case format:

For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

Example 1:

Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).

Example 2:

Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.

Example 3:

Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.

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.

Approach overview

Problem Overview: You’re given a reference to a node in a connected undirected graph. Each node contains a value and a list of neighbors. The task is to create a deep copy of the entire graph so that every node and edge is duplicated without sharing references with the original graph.

Approach 1: Depth-First Search (DFS) Graph Cloning (O(V + E) time, O(V) space)

This approach treats cloning as a graph traversal problem. Starting from the given node, perform a recursive Depth-First Search. For each visited node, create a clone and store the mapping from original node to cloned node in a hash map. The hash map prevents duplicate cloning and also helps handle cycles in the graph. When DFS visits a neighbor, check the map: if the neighbor hasn’t been cloned yet, recursively clone it; otherwise reuse the stored clone. Each edge is processed once while building the neighbor list for the copied node. The total complexity is O(V + E) time because every vertex and edge is traversed once, and O(V) space for the recursion stack and hash map.

This method is concise and mirrors the natural recursive structure of graph traversal. It works especially well when implementing graph algorithms recursively and when the graph depth is manageable.

Approach 2: Breadth-First Search (BFS) Graph Cloning (O(V + E) time, O(V) space)

The BFS approach clones the graph level by level using a queue. Start by cloning the initial node and pushing the original node into a queue. Maintain a hash map that maps each original node to its cloned counterpart. While the queue isn’t empty, pop a node, iterate through its neighbors, and check if each neighbor has already been cloned. If not, create the clone, add it to the map, and push the original neighbor into the queue for later processing. Then append the cloned neighbor to the neighbor list of the current cloned node. This guarantees that each node is cloned exactly once while preserving the graph structure.

BFS avoids recursion and uses an explicit queue, which can be safer for very deep graphs where recursion depth might be a concern. Like DFS, it relies on a Hash Table to maintain the original-to-clone mapping and correctly reconstruct edges in the graph. The complexity remains O(V + E) time and O(V) space.

Recommended for interviews: Both DFS and BFS are accepted optimal solutions. Interviewers usually expect a graph traversal with a hash map to track cloned nodes. DFS tends to be slightly shorter to write and demonstrates comfort with recursive graph traversal, while BFS shows iterative control using a queue. Explaining why the hash map is required (to avoid cloning nodes multiple times and to handle cycles) is often the key signal that you fully understand the problem.

Approach 1: Depth-First Search (DFS) for Graph Cloning

The Depth-First Search (DFS) approach is one of the most intuitive ways to solve the graph cloning problem. Here, we will recursively explore each node starting from the root (Node 1) and keep a map to store already cloned nodes, ensuring each node is cloned once.

For each node, we:

  • Check if the node is already cloned; if so, return the cloned instance to avoid cycles.
  • Create a new copy of the node.
  • Iteratively clone all its neighbors and add the clone references to the new node's neighbor list.
  • Return the cloned node.
class Node:
    def __init__(self, val = 0, neighbors = None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []

class Solution:
    def __init__(self):
        self.visited = {}

    def cloneGraph(self, node: 'Node') -> 'Node':
        if not node:
            return None
        
        if node in self.visited:
            return self.visited[node]
        
        clone_node = Node(node.val, [])
        self.visited[node] = clone_node

        if node.neighbors:
            clone_node.neighbors = [self.cloneGraph(n) for n in node.neighbors]

        return clone_node
import java.util.*;

class Node {
    public int val;
    public List<Node> neighbors;
    public Node() {
        val = 0;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val) {
        val = _val;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val, ArrayList<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}

class Solution {
    private Map<Node, Node> visited = new HashMap<>();

    public Node cloneGraph(Node node) {
        if (node == null) return null;

        if (visited.containsKey(node)) {
            return visited.get(node);
        }

        Node cloneNode = new Node(node.val, new ArrayList<>());
        visited.put(node, cloneNode);

        for (Node neighbor : node.neighbors) {
            cloneNode.neighbors.add(cloneGraph(neighbor));
        }
        return cloneNode;
    }
}
#include <vector>
#include <unordered_map>
using namespace std;

class Node {
public:
    int val;
    vector<Node*> neighbors;
    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }
    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }
    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};

class Solution {
public:
    unordered_map<Node*, Node*> visited;

    Node* cloneGraph(Node* node) {
        if (!node) return NULL;
        if (visited.find(node) != visited.end())
            return visited[node];
        
        Node* cloneNode = new Node(node->val);
        visited[node] = cloneNode;
        
        for (auto neighbor : node->neighbors) {
            cloneNode->neighbors.push_back(cloneGraph(neighbor));
        }
        return cloneNode;
    }
};
function Node(val, neighbors) {
    this.val = val;
    this.neighbors = neighbors ? neighbors : [];
};

var cloneGraph = function(node) {
    let visited = new Map();

    function dfs(node) {
        if (!node) return node;
        if (visited.has(node)) return visited.get(node);

        let cloneNode = new Node(node.val);
        visited.set(node, cloneNode);

        node.neighbors.forEach(neighbor => {
            cloneNode.neighbors.push(dfs(neighbor));
        });

        return cloneNode;
    }

    return dfs(node);
};
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NODES 101

typedef struct Node {
    int val;
    struct Node** neighbors;
    int numNeighbors;
} Node;

Node* cloneGraph(Node* node, Node** cloneMap);

Node* cloneGraphUtil(Node* node, Node** cloneMap) {
    if (node == NULL) return NULL;

    if (cloneMap[node->val]) return cloneMap[node->val];

    Node* cloneNode = (Node*)malloc(sizeof(Node));
    cloneNode->val = node->val;
    cloneNode->numNeighbors = node->numNeighbors;
    cloneNode->neighbors = (Node**)malloc(sizeof(Node*) * node->numNeighbors);
    cloneMap[node->val] = cloneNode;

    for (int i = 0; i < node->numNeighbors; i++) {
        cloneNode->neighbors[i] = cloneGraphUtil(node->neighbors[i], cloneMap);
    }
    
    return cloneNode;
}

Node* cloneGraph(Node* node) {
    Node* cloneMap[MAX_NODES] = {NULL};
    return cloneGraphUtil(node, cloneMap);
}
using System;
using System.Collections.Generic;

public class Node {
    public int val;
    public IList<Node> neighbors;
    public Node() {
        val = 0;
        neighbors = new List<Node>();
    }
    public Node(int _val) {
        val = _val;
        neighbors = new List<Node>();
    }
    public Node(int _val, List<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}

public class Solution {
    private Dictionary<Node, Node> visited = new Dictionary<Node, Node>();

    public Node CloneGraph(Node node) {
        if (node == null) return null;
        if (visited.ContainsKey(node))
            return visited[node];

        Node cloneNode = new Node(node.val, new List<Node>());
        visited[node] = cloneNode;

        foreach (Node neighbor in node.neighbors) {
            cloneNode.neighbors.Add(CloneGraph(neighbor));
        }

        return cloneNode;
    }
}

This Python implementation uses a dictionary visited to map original nodes to their clones. The cloneGraph function recursively creates and returns deep copies by processing neighbors recursively.

Complexity

Time Complexity: O(V+E).

Space Complexity: O(V) for recursion and visited.

Try this approach in the editor

Approach 2: Breadth-First Search (BFS) for Graph Cloning

An alternative approach is to use Breadth-First Search (BFS), which is iterative in nature. Here, we utilize a queue to help explore each node level by level, preventing deep recursion and managing each node's clone in a breadth-wise manner.

In this BFS approach:

  • We initialize a queue with the starting node.
  • Use a map to store cloned nodes and a visited state.
  • Iteratively process nodes from the queue—cloning nodes, establishing clone-linking relationships, and enqueuing unvisited nodes.
  • Once the queue is empty, cloning and linking are complete.
from collections import deque

class Node:
    def __init__(self, val = 0, neighbors = None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []

class Solution:
    def cloneGraph(self, node: 'Node') -> 'Node':
        if not node:
            return None

        visited = {}
        queue = deque([node])
        visited[node] = Node(node.val, [])

        while queue:
            n = queue.popleft()
            for neighbor in n.neighbors:
                if neighbor not in visited:
                    visited[neighbor] = Node(neighbor.val, [])
                    queue.append(neighbor)
                visited[n].neighbors.append(visited[neighbor])

        return visited[node]
import java.util.*;

class Node {
    public int val;
    public List<Node> neighbors;
    public Node() {
        val = 0;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val) {
        val = _val;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val, ArrayList<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}

class Solution {
    public Node cloneGraph(Node node) {
        if (node == null) return null;

        Map<Node, Node> visited = new HashMap<>();
        Queue<Node> queue = new LinkedList<>();
        queue.add(node);
        visited.put(node, new Node(node.val, new ArrayList<>()));
        
        while (!queue.isEmpty()) {
            Node n = queue.poll();
            for (Node neighbor : n.neighbors) {
                if (!visited.containsKey(neighbor)) {
                    visited.put(neighbor, new Node(neighbor.val, new ArrayList<>()));
                    queue.add(neighbor);
                }
                visited.get(n).neighbors.add(visited.get(neighbor));
            }
        }
        return visited.get(node);
    }
}
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;

class Node {
public:
    int val;
    vector<Node*> neighbors;
    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }
    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }
    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};

class Solution {
public:
    Node* cloneGraph(Node* node) {
        if (!node) return NULL;
        unordered_map<Node*, Node*> visited;
        queue<Node*> q;
        q.push(node);
        visited[node] = new Node(node->val);

        while (!q.empty()) {
            auto n = q.front(); q.pop();
            for (auto neighbor : n->neighbors) {
                if (visited.find(neighbor) == visited.end()) {
                    visited[neighbor] = new Node(neighbor->val);
                    q.push(neighbor);
                }
                visited[n]->neighbors.push_back(visited[neighbor]);
            }
        }
        return visited[node];
    }
};
function Node(val, neighbors) {
    this.val = val;
    this.neighbors = neighbors ? neighbors : [];
};

var cloneGraph = function(node) {
    if (!node) return null;
    const visited = new Map();
    const queue = [node];
    visited.set(node, new Node(node.val));

    while (queue.length) {
        const n = queue.shift();
        for (const neighbor of n.neighbors) {
            if (!visited.has(neighbor)) {
                visited.set(neighbor, new Node(neighbor.val));
                queue.push(neighbor);
            }
            visited.get(n).neighbors.push(visited.get(neighbor));
        }
    }
    return visited.get(node);
};
using System;
using System.Collections.Generic;

public class Node {
    public int val;
    public IList<Node> neighbors;
    public Node() {
        val = 0;
        neighbors = new List<Node>();
    }
    public Node(int _val) {
        val = _val;
        neighbors = new List<Node>();
    }
    public Node(int _val, List<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}

public class Solution {
    public Node CloneGraph(Node node) {
        if (node == null) return null;

        Dictionary<Node, Node> visited = new Dictionary<Node, Node>();
        Queue<Node> queue = new Queue<Node>();
        queue.Enqueue(node);
        visited[node] = new Node(node.val, new List<Node>());

        while (queue.Count > 0) {
            var n = queue.Dequeue();
            foreach (var neighbor in n.neighbors) {
                if (!visited.ContainsKey(neighbor)) {
                    visited[neighbor] = new Node(neighbor.val, new List<Node>());
                    queue.Enqueue(neighbor);
                }
                visited[n].neighbors.Add(visited[neighbor]);
            }
        }
        return visited[node];
    }
}

The Python BFS implementation uses a deque for iterative traversal and a dictionary visited to record cloned nodes. It features level-wise cloning and linking of the nodes, ensuring all nodes are cloned and linked efficiently.

Complexity

Time Complexity: O(V+E).

Space Complexity: O(V).

Try this approach in the editor

Approach 3: Hash Table + DFS

We use a hash table g to record the correspondence between each node in the original graph and its copy, and then perform depth-first search.

We define the function dfs(node), which returns the copy of the node. The process of dfs(node) is as follows:

  • If node is null, then the return value of dfs(node) is null.
  • If node is in g, then the return value of dfs(node) is g[node].
  • Otherwise, we create a new node cloned and set the value of g[node] to cloned. Then, we traverse all the neighbor nodes nxt of node and add dfs(nxt) to the neighbor list of cloned.
  • Finally, return cloned.

In the main function, we return dfs(node).

The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes.

/**
 * Definition for _Node.
 * class _Node {
 *     val: number
 *     neighbors: _Node[]
 *
 *     constructor(val?: number, neighbors?: _Node[]) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.neighbors = (neighbors===undefined ? [] : neighbors)
 *     }
 * }
 *
 */

function cloneGraph(node: _Node | null): _Node | null {
    const g: Map<_Node, _Node> = new Map();
    const dfs = (node: _Node | null): _Node | null => {
        if (!node) {
            return null;
        }
        if (g.has(node)) {
            return g.get(node);
        }
        const cloned = new _Node(node.val);
        g.set(node, cloned);
        for (const nxt of node.neighbors) {
            cloned.neighbors.push(dfs(nxt));
        }
        return cloned;
    };
    return dfs(node);
}
/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Neighbors []*Node
 * }
 */

func cloneGraph(node *Node) *Node {
	g := map[*Node]*Node{}
	var dfs func(node *Node) *Node
	dfs = func(node *Node) *Node {
		if node == nil {
			return nil
		}
		if n, ok := g[node]; ok {
			return n
		}
		cloned := &Node{node.Val, []*Node{}}
		g[node] = cloned
		for _, nxt := range node.Neighbors {
			cloned.Neighbors = append(cloned.Neighbors, dfs(nxt))
		}
		return cloned
	}
	return dfs(node)
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Depth-First Search (DFS) for Graph Cloning

Time Complexity: O(V+E).

Space Complexity: O(V) for recursion and visited.

Breadth-First Search (BFS) for Graph Cloning

Time Complexity: O(V+E).

Space Complexity: O(V).

Hash Table + DFS–

Complexity analysis

ApproachTimeSpaceWhen to Use
Depth-First Search (DFS) with Hash MapO(V + E)O(V)Preferred when recursion is acceptable and you want a concise graph traversal solution
Breadth-First Search (BFS) with QueueO(V + E)O(V)Useful when avoiding recursion or when implementing iterative graph traversal

Frequently asked questions

Is Clone Graph easy or hard?

Clone Graph is generally rated Medium difficulty. The main challenge is recognizing that graphs may contain cycles, so you must store visited nodes in a hash map to avoid infinite loops and duplicate clones.

How to solve Clone Graph in O(n)?

Treat the graph cloning process as a traversal problem. Use DFS or BFS starting from the given node and maintain a hash map that stores the mapping between original nodes and their cloned versions. Each node is visited once and each edge is processed once, giving O(V + E) time, which is linear relative to the graph size.

What is the best approach for Clone Graph?

The optimal approach uses graph traversal with a hash map to track already cloned nodes. Both Depth-First Search (DFS) and Breadth-First Search (BFS) work well. Each node is cloned once and stored in a map from original node to copied node, giving O(V + E) time complexity where V is the number of vertices and E is the number of edges.

What data structure is used in Clone Graph?

The core data structure is a hash map (or dictionary) that maps each original node to its cloned node. The traversal itself uses either recursion for DFS or a queue for BFS, along with adjacency lists stored in each graph node.

What is the time complexity of Clone Graph?

Clone Graph runs in O(V + E) time because every vertex and every edge in the graph is visited exactly once during traversal. The hash map lookup for already-cloned nodes is O(1) on average, so it doesn’t increase the overall complexity.

Clone Graph Python or Java solution approach?

Both Python and Java solutions typically use a hash map plus DFS or BFS traversal. In Python, a dictionary stores the mapping between original and cloned nodes, while Java implementations usually use HashMap<Node, Node>. The logic remains the same across languages with O(V + E) time complexity.

Is Clone Graph asked at Google, Amazon, or Meta?

Clone Graph appears frequently in interviews at large tech companies including Amazon, Google, Meta, and Microsoft. It tests understanding of graph traversal, deep copying of structures, and handling cycles using hash maps.

Comments

Now write it yourselfClose this page and solve Clone Graph in the editor, without looking.
Practise Clone Graph