Graph Theory37 sections · 1633 units
Open in Course

LeetCode 886 Possible Bipartition - Algorithm

Same core logic

The algorithm is almost identical to :

1.1. Build adjacency list from dislikes.

2.2. Create color array of size n+1n+1, all 1-1.

3.3. For each person ii from 11 to nn: if color[i] == -1, run BFS from ii.

4.4. In BFS: color start as 00.

For each neighbor: if uncolored, assign opposite color, add to queue. If same color, return false.

5.5. If all done without conflict, return true.

This runs in O(V+E)O(V + E) time and uses O(V)O(V) space.