Given a node of a connected, undirected graph, return a deep copy of the whole graph. Each node holds a value, val, and a list of its neighbours, and the values run from 1 to the number of nodes. Every node of the copy must be new, with the same value and the same neighbours, in the same order.
Examples
Example 1:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Example 2:
Input: adjList = [[]]
Output: [[]]
Explanation: one node, no edges.
Example 3:
Input: adjList = []
Output: []
Example 4:
Input: adjList = [[2],[1]]
Output: [[2],[1]]
Constraints
0 <= n <= 100
The graph is connected and undirected: j in adjList[i] implies i+1 in adjList[j-1]. No self-loops.
Prerequisites
Graph traversal — DFS and BFS, and a visited set as the thing that makes both terminate. Union-find for connectivity questions; topological order for dependency ones.
How to think about it
1. A Map From Original to Copy Optimal
Intuition
Copying a graph means copying nodes AND rewiring their neighbours to the copies — and cycles make that dangerous, because following neighbours blindly recurses forever. One map from original node to its copy solves both problems at once: it is the memo that terminates the recursion, and it guarantees each original maps to exactly one copy, so no copy accidentally points back into the original graph. Saying that the map does two jobs is the interview answer.
Algorithm
1. DFS from the node you are given; if it is already in the map, return its copy. 2. Otherwise create the copy, record it BEFORE recursing, then copy each neighbour. 3. Return the copy of the node you were given.
Time & Space
Time O(nodes + edges). Space O(nodes) for the map.
2. The Map Kept Local
Intuition
The same copy, the map held by the call instead of the object. cloneGraph answers nothing for nothing, makes an empty map, and starts the copy from the node given; the helper reads and fills that one map, handed to it on every call in Java and seen from cloneGraph's own scope in Python, where the helper is a function nested inside it. Nothing is kept on the object between calls, so there is nothing to make new at the top, and the helper is not a method a caller can reach. The copying is the first approach's: a node met again hands back its copy, and a new one is recorded before its neighbours are copied.
Algorithm
1. DFS from the node you are given; if it is already in the map, return its copy. 2. Otherwise create the copy, record it BEFORE recursing, then copy each neighbour. 3. Return the copy of the node you were given.
Time & Space
Time O(nodes + edges). Space O(nodes) for the map.