Is Graph Bipartite?
Explanation & Solution
Description
Given an undirected graph represented as an adjacency list, where graph[i] is a list of nodes that node i is connected to, return true if and only if the graph is bipartite.
A graph is bipartite if the nodes can be partitioned into two sets such that no two adjacent nodes belong to the same set. Equivalently, the graph can be colored with two colors so that every edge connects nodes of different colors.
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
Output: false
Explanation: There is no way to partition the nodes into two groups such that every edge connects nodes from different groups. For instance, nodes 0, 1, and 2 are all mutually connected, forming a triangle (odd cycle), which makes the graph non-bipartite.
Constraints
graph.length == n1 <= n <= 1000 <= graph[i].length < n0 <= graph[i][j] <= n - 1graph[i][j] != i(no self-loops)- If
graph[i]containsj, thengraph[j]containsi(undirected) - The graph may be disconnected
Approach
Graphs pattern
1. Initialize a Color Array
- Create an array
colorof lengthn, filled with-1 -1means the node has not been visited yet- We will use
0and1as the two colors
2. Iterate Over All Nodes
- For each node
startfrom0ton - 1: - If the node is already colored, skip it
- Otherwise, start a BFS from this node
- This outer loop ensures we handle disconnected components
3. BFS Coloring
- Assign color
0to the starting node and push it into the queue - While the queue is not empty:
- Dequeue the front node
- For each neighbor of the current node:
- If the neighbor is uncolored (
-1), assign it the opposite color (1 - color[node]) and enqueue it - If the neighbor has the same color as the current node, a conflict is found — return
false
4. Return True
- If BFS completes for all components without any conflict, the graph is bipartite — return
true
Key Insight
- A graph is bipartite if and only if it contains no odd-length cycles. BFS naturally explores nodes level by level, alternating colors at each level. If two adjacent nodes end up with the same color, it means there is an odd cycle — making 2-coloring impossible. By running BFS from every unvisited node, we also handle disconnected graphs correctly.
Visualization
Press play to start 2-coloring check