Back to Practice Dashboard
Top 150 InterviewMedium

Clone Graph

Learn how to solve the 'Clone Graph' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Medium

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 of its neighbors (List[Node]).

The graph is represented as an adjacency list. Implement a function cloneGraph(adjList: List[List[int]]) -> List[List[int]] where adjList[i] represents the neighbors of node i+1 (1-indexed). Return the adjacency list of the cloned graph.

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

Examples

Example 1
Input
adjList = [[2,4],[1,3],[2,4],[1,3]]
Output
[[2,4],[1,3],[2,4],[1,3]]
Explanation

Node 1's neighbors are 2 and 4. Node 2's neighbors are 1 and 3. Node 3's neighbors are 2 and 4. Node 4's neighbors are 1 and 3.

Example 2
Input
adjList = [[]]
Output
[[]]
Explanation

The graph contains only one node with value 1 and no neighbors.

Need a Hint?
Represent graph node connections as an adjacency list/matrix, then use standard BFS or DFS graph traversal.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor