Clone Graph

Medium
DFS

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.

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

Test case format:

  • The graph is represented as an adjacency list
  • Each element is a list of neighbors for the node at that index (1-indexed)
  • The first element's neighbors define node 1's connections, etc.

Example Graph:

1 --- 2
|     |
4 --- 3

Adjacency list: [[2,4],[1,3],[2,4],[1,3]]

DFS Approach:

  1. Create a hashmap to store {original node -> cloned node}
  2. For each node, create its clone if not already created
  3. Recursively clone all neighbors
  4. Connect the cloned node to its cloned neighbors

Key Insight: The hashmap serves two purposes:

  • Tracks visited nodes to avoid infinite loops in cyclic graphs
  • Maps original to clone for building connections

Example 1

Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: Node 1 connects to 2,4. Node 2 connects to 1,3. Node 3 connects to 2,4. Node 4 connects to 1,3. The clone has the same structure.

Example 2

Input: adjList = [[]]
Output: [[]]
Explanation: Single node with no neighbors.

Example 3

Input: adjList = []
Output: []
Explanation: Empty 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.
  • The Graph is connected and all nodes can be visited starting from the given node.
Show Hints (4)
Hint 1: How do you handle cycles? You need to remember which nodes you've already cloned.
Hint 2: A hashmap from original node to cloned node helps track visited nodes and build connections.
Hint 3: Process: clone current node, recursively clone neighbors, connect clone to cloned neighbors.
Hint 4: Both DFS and BFS work here. DFS is simpler with recursion.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?