You're given a reference to a node in a connected undirected graph. Your task is to create a complete deep copy (clone) of the entire graph.

Each node in the graph contains:

  • An integer val (the node's value)
  • A List<Node> of its neighbors

The graph is connected, meaning you can reach any node from any other node. You need to return a reference to the cloned version of the given node.

Important: The cloned graph should be completely independent of the original - modifying the clone shouldn't affect the original graph.

Node Definition:

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

Input & Output

example_1.py — Simple 2-node cycle
$ Input: adjList = [[2],[1]]
Output: [[2],[1]]
💡 Note: The graph has 2 nodes. Node 1 is connected to node 2, and node 2 is connected to node 1. The cloned graph maintains the same structure.
example_2.py — 4-node complex graph
$ Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
💡 Note: Node 1 connects to nodes 2 and 4. Node 2 connects to nodes 1 and 3. Node 3 connects to nodes 2 and 4. Node 4 connects to nodes 1 and 3. The clone preserves all connections.
example_3.py — Single node
$ Input: adjList = [[]]
Output: [[]]
💡 Note: The graph contains only one node with no neighbors. The cloned graph is identical.

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 you can visit all nodes from the given node

Visualization

Tap to expand
Clone Graph - BFS Approach INPUT Original Graph 1 2 neighbors:[2] neighbors:[1] Adjacency List Input: adjList = [[2],[1]] Connected, Undirected 2 Nodes, 1 Edge Starting node: 1 ALGORITHM STEPS 1 Initialize Create HashMap + Queue Map: old node --> clone 2 Clone Start Node Clone node 1, add to map Enqueue node 1 3 BFS Traversal Process each neighbor Clone if not visited 4 Link Neighbors Connect clone neighbors From HashMap lookup Queue State [1] --> [2] --> [] HashMap 1-->1', 2-->2' FINAL RESULT Cloned Graph (Deep Copy) 1' 2' neighbors:[2'] neighbors:[1'] Output: [[2],[1]] OK - Deep Copy Independent from original Same structure, new refs Key Insight: BFS ensures we visit each node exactly once. The HashMap serves dual purpose: tracks visited nodes to prevent cycles AND maps original nodes to their clones for neighbor linking. Time: O(V+E), Space: O(V) TutorialsPoint - Clone Graph | BFS Approach
Asked in
Meta 45 Google 38 Amazon 32 Microsoft 28 Apple 15
89.2K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen