Maintained by Vikas Dulgunde, software engineer
You receive a graph encoded as an adjacency list. The list is an array where the entry at index i holds the neighbors of node i, and every value is a node index in the same array.
Your job is to produce a fresh adjacency list that describes the identical graph. Node i in the copy must point to the same set of neighbors as node i in the input, and the neighbors inside each list must appear in the same order they were given.
The graph is undirected, so if node a lists b as a neighbor then b lists a too. It is connected when it has at least one node, which means a traversal from any starting node can reach every other node. There are no self-loops and no duplicate edges.
An empty input (no nodes) should give back an empty list, and a single node with no edges should give back a list holding one empty neighbor list.
A four-node cycle 0-1-2-3-0. The copy repeats each node's neighbor list in the original order, so the result matches the input value for value.
Two nodes joined by a single edge. Node 0 points to node 1 and node 1 points back to node 0, and the copy preserves both.
One node with no edges. The copy still has one entry, an empty neighbor list.
Visible test cases
The output has the same shape as the input: one neighbor list per node, with neighbors in the same order. What is the simplest way to reproduce that shape?
If you walk the graph from a starting node, a visited marker per node stops you from looping forever on cycles like 0-1-2-3-0.
You can copy every node's neighbor list as you reach it during a traversal, or you can just rebuild each list directly by index since the values are plain integers.
Treat the input as a real graph: start at node 0, walk outward breadth first, and record each node's neighbors into a fresh list as you visit it. A visited array keeps the walk from cycling.
Because each node is identified by its index and neighbors are plain integers, an independent copy is just a new array holding a fresh copy of every neighbor list. No graph walk is needed.