Is Graph Bipartite? (LeetCode 785): Solution and Explanation
You get an undirected graph as an adjacency list, possibly split into several disconnected pieces. Decide whether its nodes can be split into two groups so that every edge goes between the groups and none stays inside one.
Watch it run step by step
Try your own input and write the code →Intuition
Trying every way to split n nodes into two groups is 2ⁿ possibilities, so brute force is out. The useful observation is that the split is almost forced. Once you put one node in group A, all its neighbors must be in group B, all of their neighbors in group A, and so on. There is no choice after the first node of each connected piece.
That turns the problem into two-coloring. Start from any uncolored node, give it one color and spread outward, giving every neighbor the opposite color. If you ever find an edge whose two ends already have the same color, the graph cannot be split, which happens exactly when the graph contains a cycle of odd length.
Because the graph may be disconnected, one search is not enough. You loop over all nodes and start a fresh BFS from each node that is still uncolored. Each component can be colored independently, since there are no edges between components to cause conflicts. BFS is a natural fit because it processes the graph layer by layer, and layers alternate colors, but DFS works just as well.
A small example makes the odd cycle idea concrete. In a square of four nodes connected in a ring, colors alternate 1, -1, 1, -1 and the fourth node's neighbor back to the start has the opposite color, so the ring is bipartite. In a triangle, the third node is adjacent to both of the first two, which already have different colors, so it cannot take either one. Every failure the algorithm reports is a version of that triangle problem stretched around a longer odd cycle.
Approach: BFS two-coloring
- Create
colorof length n with 0 for uncolored, 1 for one side and -1 for the other. - For each node
ithat is still uncolored, run a BFS starting from it. - In the BFS, color the start node 1 and add it to the queue.
- Pop a node and look at each neighbor. If the neighbor has the same color as the node, return False.
- If the neighbor is uncolored, give it
-color[node]and enqueue it. - If every BFS finishes without a conflict, return True.
Step-by-step example
graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
- Node 0 is uncolored, so BFS starts there and colors it 1.
- Popping node 0 colors its neighbors 1, 2 and 3 with -1 and enqueues them.
- Popping node 1, its neighbor 0 has color 1, which is fine. Its neighbor 2 has color -1, the same as node 1.
- That edge between nodes 1 and 2 has both ends on the same side, so the function returns False. Nodes 0, 1 and 2 form a triangle, an odd cycle.
Code: Python, Java, C++
1class Solution:
2 def isBipartite(self, graph: List[List[int]]) -> bool:
3 n = len(graph)
4 color = [0] * n # 0 = uncolored, 1 = red, -1 = blue
5
6 def bfs(start):
7 queue = [start]
8 color[start] = 1
9 while queue:
10 node = queue.pop(0)
11 for neighbor in graph[node]:
12 if color[neighbor] == color[node]:
13 return False
14 if color[neighbor] == 0:
15 color[neighbor] = -color[node]
16 queue.append(neighbor)
17 return True
18
19 for i in range(n):
20 if color[i] == 0:
21 if not bfs(i):
22 return False
23 return True1class Solution {
2 public boolean isBipartite(int[][] graph) {
3 int n = graph.length;
4 int[] color = new int[n];
5
6 for (int i = 0; i < n; i++) {
7 if (color[i] == 0 && !bfs(graph, color, i)) {
8 return false;
9 }
10 }
11 return true;
12 }
13
14 private boolean bfs(int[][] graph, int[] color, int start) {
15 Queue<Integer> queue = new LinkedList<>();
16 queue.add(start);
17 color[start] = 1;
18
19 while (!queue.isEmpty()) {
20 int node = queue.poll();
21 for (int neighbor : graph[node]) {
22 if (color[neighbor] == color[node]) return false;
23 if (color[neighbor] == 0) {
24 color[neighbor] = -color[node];
25 queue.add(neighbor);
26 }
27 }
28 }
29 return true;
30 }
31}1class Solution {
2public:
3 bool isBipartite(vector<vector<int>>& graph) {
4 int n = graph.size();
5 vector<int> color(n, 0);
6
7 for (int i = 0; i < n; i++) {
8 if (color[i] == 0 && !bfs(graph, color, i)) {
9 return false;
10 }
11 }
12 return true;
13 }
14
15private:
16 bool bfs(vector<vector<int>>& graph, vector<int>& color, int start) {
17 queue<int> q;
18 q.push(start);
19 color[start] = 1;
20
21 while (!q.empty()) {
22 int node = q.front();
23 q.pop();
24 for (int neighbor : graph[node]) {
25 if (color[neighbor] == color[node]) return false;
26 if (color[neighbor] == 0) {
27 color[neighbor] = -color[node];
28 q.push(neighbor);
29 }
30 }
31 }
32 return true;
33 }
34};Time and space complexity
O(V + E)
Every node is colored and enqueued once and every edge is examined from both ends, assuming a queue with constant-time removal. The reference uses list.pop(0), which shifts the list, so a deque is the better choice for large graphs.
O(V)
The color array and the queue each hold at most V nodes.
Other approaches
DFS coloring (time O(V + E), space O(V))
Recursively color neighbors with the opposite color and fail on a conflict. Same idea and complexity; recursion depth can reach V on long chains.
Union-find (time O(E × α(V)), space O(V))
For every node, union all of its neighbors together, since they must share a side, and fail if a node ends up in the same set as one of its neighbors.
Common mistakes
- Running BFS only from node 0 misses other components; a conflict in a disconnected piece would go undetected.
- Coloring a node when it is dequeued instead of when it is enqueued lets the same node be added several times with possibly different colors.
- Using
queue.pop(0)on a Python list makes each removal O(V); usecollections.dequefor real linear time. - Treating isolated nodes with empty adjacency lists as errors; they are trivially bipartite.
Frequently asked questions
How do you check if a graph is bipartite?
Try to color it with two colors so that every edge connects different colors, using BFS or DFS. If you ever find an edge whose ends share a color, the graph is not bipartite.
What makes a graph not bipartite?
An odd-length cycle. Going around an odd cycle forces the starting node to need both colors, which is the conflict the coloring detects.
BFS or DFS for is graph bipartite?
Both work with the same O(V + E) complexity. BFS colors layer by layer, while DFS is shorter to write but can hit recursion limits on long paths.
Why loop over every node?
The graph can be disconnected. Each component has to be colored separately, otherwise conflicts in components not reachable from the first node are missed.