Graph Theory37 sections · 1633 units
Open in Course

LeetCode 886 Possible Bipartition - Building the Graph

Edge list to adj list

The input gives you an edge list: dislikes = [[1,2],[1,3],[2,4]] means person 11 dislikes 22, person 11 dislikes 33, person 22 dislikes 44. You need an adjacency list to run BFS. Create graph as an array of n+1n+1 empty lists (people are 11-indexed).

For each pair [a, b], add bb to graph[a] and aa to graph[b]. Dislikes are mutual, so edges go both ways. This converts the input into a graph you can traverse.