Video in progress
You need to split a graph into two groups so that every edge connects different groups (bipartite). How do you check this?
I two-color it with BFS or DFS: the starting node gets 0, its neighbors get 1, their neighbors get 0 again. If a neighbor already has the same color, the graph isn't bipartite, meaning it has an odd-length cycle. O(V + E).
📖 Answer
A real example: splitting employees into two shifts so that "people who can't work together" don't land in the same shift.
static boolean isBipartite(List<List<Integer>> g) {
int n = g.size();
int[] color = new int[n];
Arrays.fill(color, -1);
Deque<Integer> q = new ArrayDeque<>();
for (int s = 0; s < n; s++) {
if (color[s] != -1) continue; // the graph may consist of several components
color[s] = 0;
q.add(s);
while (!q.isEmpty()) {
int u = q.poll();
for (int v : g.get(u)) {
if (color[v] == -1) {
color[v] = 1 - color[u];
q.add(v);
} else if (color[v] == color[u]) {
return false; // odd cycle
}
}
}
}
return true;
}
The most common mistake is starting the BFS only from node 0. If the graph is disconnected, an odd cycle in another component goes unnoticed. That's what the outer for is for.
Why specifically an odd cycle? Along a cycle the colors alternate 0, 1, 0, 1... With an even length you return to the start with the right color; with an odd length the last node ends up with the same color as the first.
An alternative is Union-Find: you merge all the neighbors of each node u into one set; if u ends up in the same set as one of its neighbors, it isn't bipartite. It's handy when edges arrive online.
The interviewer may ask "what if there are three shifts?". Two-coloring is linear, while three-coloring is NP-complete. If you mention that difference, it's a good signal.
Sign up to mark studied questions and save your progress.