← Visualizers
Traversal · 1.G · Dislike Graph Bipartition LeetCode 886

Possible Bipartition / visualized

Given n people (1-indexed) and an array dislikes where dislikes[i] = [a, b] means person a and b dislike each other. Return true if and only if it is possible to split everyone into two groups.

Group Placement & Dislike Graph

idle
INVARIANT Graph Coloring Equivalence: A valid 2-group partitioning exists iff the dislike graph is bipartite (0 odd cycles). We construct the adjacency graph from dislikes and assign alternating colors 1 (Group A) and 2 (Group B). Any edge between nodes of the same color violates the partition.
Group A (Blue)
Group B (Amber)
Current Person:-
Conflict:None
Press Run to begin.
0 / 0

Java 21 Solution

INTERVIEW SCRIPT

How to Explain Possible Bipartition to an Interviewer

1. Graph Modeling from Real-World Constraints

"People are nodes (1 to n). Dislike pairs are undirected edges: two people who dislike each other cannot share the same group. This is 2-coloring."

2. 1-Indexed vs 0-Indexed Safety

"The input is 1-indexed. Allocate arrays of size $n+1$ to avoid off-by-one errors: color = new int[n + 1]."

3. BFS/DFS Conflict Invariant

"Iterate 1..n. For each uncolored component, assign Color 1. For each neighbor $v$, if uncolored assign $3 - color[u]$ (swaps between 1 and 2). If neighbor has same color, return false immediately."

4. Complexity Mastery

"Building the graph takes $O(E)$. BFS visits each person and dislike edge once. Total time is $O(V + E)$ and auxiliary space is $O(V + E)$."

O(V + E) time · O(V + E) space · Dislike graph 2-coloring · Dual granularity navigation