You get one node of a connected, undirected graph. Each node has an integer val and a list neighbors of the nodes it links to.
Build a deep copy: a brand-new node for every node in the graph, linked to each other exactly as the originals are, in the same neighbour order. Return the copy of the node you were given. No copied node may point at an original one.
Tests describe the graph as an adjacency list: row i lists the neighbours of the node with val i + 1, and you are handed the node with val 1. An empty list means there is no graph, and you get null.
Example 1
Input: adjList = [[2, 3], [1, 3], [1, 2, 4], [3]] Output: [[2, 3], [1, 3], [1, 2, 4], [3]] Why: a triangle 1-2-3 with 4 hanging off 3, rebuilt
2 more examples and the constraints
Example 2
Input: adjList = [[2], [1]] Output: [[2], [1]] Why: two new nodes, linked to each other
Example 3
Input: adjList = [] Output: [] Why: no nodes, so the copy is null
Constraints
- 0 ≤ number of nodes ≤ 100
- 1 ≤ Node.val ≤ 100, and every val is different
- No node links to itself, and no link appears twice
- Every node can be reached from the one you are given
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursive DFS + mapO(V + E)
- BFS + mapO(V + E)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 nodes | Verdict |
|---|---|---|---|
| Recursive DFS + map | O(V + E) | Passes; shortest to write | |
| BFS + map | O(V + E) | Best; no deep recursion |
V = number of nodes, E = number of links.
Edge cases to test
- Empty graph. The input is null; return null, not a new node.
- One node. [[]] gives a single new node with no neighbours.
- Cycles. A ring of five nodes comes back to the start; the map stops the walk from going round forever.
- Neighbour order. The copy must list neighbours in the same order as the original, as in [[3, 2], [3, 1], [2, 1]].
Common mistakes
- Storing the copy in the map only after copying its neighbours, so a cycle recurses forever.
- Appending the original neighbour instead of its copy, so the new graph points into the old one.
- Keying the map by
valand then forgetting the null input, or by a field that is not unique.
How to talk through it
- 1Clarify. Is the graph connected? Can it be empty? Must neighbour order be kept?
- 2Spot the trap. Naive recursion loops forever on a cycle and copies shared nodes twice.
- 3Add the map. Original → copy. It is both the visited set and the way to find a copy later.
- 4Code the BFS. Copy and queue on first sight; wire the link every time a neighbour is read.
- 5Test out loud. Run the empty graph, the single node and a cycle before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?