Skip to content
DeepForgeby svx
All problems
EasyData Structuresds-031

Build an Adjacency List

Problem

Build an adjacency list for an undirected graph with nodes numbered 0 to n-1.

edges is a list of [u, v] pairs. Add v to the neighbor list of u and u to the neighbor list of v; multiple edges between the same pair are kept as separate entries.

Return the list of neighbor lists, each sorted in ascending order.

Hint

Append both directions for every edge, then sort each neighbor list.

Test cases

case 1
in: [4,[[0,1],[1,2],[2,3],[0,3]]]
expected: [[1,3],[0,2],[1,3],[0,2]]
case 2
in: [3,[]]
expected: [[],[],[]]
case 3
in: [2,[[0,1],[0,1]]]
expected: [[1,1],[0,0]]
case 4
in: [4,[[0,2]]]
expected: [[2],[],[0],[]]
Starter codePython
def build_adjacency_list(n, edges):
    # Your code here
    pass

4 test cases · run your code against them in the editor