Opening the reading…
Opening the reading…
GRAPHS › DFS AND BFS ON GRAPHS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The input does not give you node objects connected by pointers. It gives one adjacency list per node: row i describes the neighbors of node i + 1. Cloning this graph therefore means producing new outer and inner lists while preserving every integer in every row. No traversal is needed to discover structure that is already written in the input.
Create one empty output row for each input row, then copy the neighbor values from row i into output row i. The values identify nodes, so copying a value preserves an edge; creating fresh vectors ensures the result does not reuse the input's list storage. The empty input is the only case with no rows to copy.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n + m) | Allocating n output rows accounts for the n term, and the inner loop processes each of the m stored neighbor entries exactly once. No entry is revisited, so the total work does not multiply across rows; in the densest allowed shape, m can be O(n^2). |
| Space | O(1) extra | The output adjacency list occupies O(n + m) space, but required output storage is excluded. Apart from that output, the algorithm keeps only the node count and loop variables, so the extra bound remains O(1) even when the input is dense. |
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> cloneGraph(vector<vector<int>>& adjList) {
if (adjList.empty()) return {};
int n = adjList.size();
vector<vector<int>> clone(n);
for (int i = 0; i < n; ++i) {
for (int v : adjList[i]) {
clone[i].push_back(v);
}
}
return clone;
}
};The index relationship is the key line of reasoning: input row i describes node i + 1, and clone[i] must describe that same node in the copy. The code copies values rather than trying to manufacture a separate mapping because node values already identify the endpoints in this representation. The newly allocated vectors provide the deep copy's independent storage.