Is Graph Bipartite?
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #785
Given an undirected graph as an adjacency list (graph[u] lists the neighbors of u), return true if the nodes can be split into two sets so that every edge connects the two sets. The graph may be disconnected.
Examples
text
[[1,2,3],[0,2],[0,1,3],[0,2]] → false (triangle 0–1–2)
[[1,3],[0,2],[1,3],[0,2]] → true ({0,2} and {1,3})Hints
- Try to color every node with one of two colors so that neighbors always differ.
- Start from each uncolored node, because the graph can have several components.
Approach
BFS 2-coloring: color[u] ∈ {-1 (unset), 0, 1}. For every uncolored node, color it 0 and BFS. Each neighbor gets the opposite color. If a neighbor already has the same color, return false.
A graph is bipartite if and only if it has no odd-length cycle. The coloring finds one exactly when it hits a same-colored edge. Union-Find also works: union every neighbor of u together, and check that u is never in the same set as its own neighbors.
Complexity
Time: O(V + E). Space: O(V).
Python solution
from collections import deque
def isBipartite(graph):
color = [-1] * len(graph)
for s in range(len(graph)):
if color[s] != -1:
continue
color[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in graph[u]:
if color[v] == -1:
color[v] = 1 - color[u]
q.append(v)
elif color[v] == color[u]:
return False
return TrueJavaScript solution
function isBipartite(graph) {
const color = new Array(graph.length).fill(-1);
for (let s = 0; s < graph.length; s++) {
if (color[s] !== -1) continue;
color[s] = 0;
const q = [s];
for (let h = 0; h < q.length; h++) {
const u = q[h];
for (const v of graph[u]) {
if (color[v] === -1) { color[v] = 1 - color[u]; q.push(v); }
else if (color[v] === color[u]) return false;
}
}
}
return true;
}