← DiffPush

Graph Representation: Matrix to Adjacency List

Baseline Graphs · Learning O(n + m) · O(n + m)

Reboxing the Warehouse Pairing Ledger

A logistics coordinator keeps pairing records as an edge list — every corridor linking two bays appears exactly once. For the routing software, though, each bay needs its own index card that opens with the bay's own number and then lists every bay directly linked to it, in the order the pairings were logged.

Input: An integer n (vertices labelled 0..n-1) and an edge list — each edge is a pair [u, v] of an undirected graph.

Output: Return the adjacency list: entry i starts with i followed by all neighbours of i in the order edges were supplied (each undirected edge contributes both directions).

Constraints

Examples

Example 1

Input: {"n":4,"edges":[[0,1],[1,2],[2,3]]}
Output: [[0,1],[1,0,2],[2,1,3],[3,2]]
Each card opens with its own bay, then the linked bays in log order.

Example 2

Input: {"n":5,"edges":[[0,1],[0,4],[1,4],[2,3]]}
Output: [[0,1,4],[1,0,4],[2,3],[3,2],[4,0,1]]
Vertex 4 picks up neighbours 0 then 1 as its two pairings are processed.

Solve this in your browser →

Also on LeetCode ↗