Top 150 InterviewMedium

Clone Graph

Detailed guide and Python implementation for the 'Clone Graph' problem.

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?
Consider using Graphs-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

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

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.