Is Graph Bipartite? - Problem
There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to.
More formally, for each v in graph[u], there is an undirected edge between node u and node v.
The graph has the following properties:
- There are no self-edges (
graph[u]does not containu) - There are no parallel edges (
graph[u]does not contain duplicate values) - If
vis ingraph[u], thenuis ingraph[v](the graph is undirected) - The graph may not be connected
A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.
Return true if and only if it is bipartite.
Input & Output
Example 1 — Simple Bipartite Graph
$
Input:
graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
›
Output:
false
💡 Note:
This forms a 4-cycle: 0-1-2-3-0. Since it's an even cycle, we expect it to be bipartite, but let's trace: if we color 0 as blue, then 1,2,3 must be red. But 1 and 2 are connected, so both can't be red. Actually this is not bipartite due to the triangle 0-1-2-0.
Example 2 — Tree Structure
$
Input:
graph = [[1,3],[0,2],[1,3],[0,2]]
›
Output:
true
💡 Note:
This forms a 4-cycle: 0-1-2-3-0. We can color it as: Set A = {0,2}, Set B = {1,3}. All edges connect different sets, so it's bipartite.
Example 3 — Odd Cycle
$
Input:
graph = [[1,2],[0,2],[0,1]]
›
Output:
false
💡 Note:
This is a triangle (3-cycle). Triangles are odd cycles and cannot be bipartite. If we color 0 as blue, then 1 and 2 must be red, but 1 and 2 are connected.
Constraints
- 1 ≤ graph.length ≤ 100
- 0 ≤ graph[u].length < graph.length
- 0 ≤ graph[u][i] ≤ graph.length - 1
- graph[u] does not contain u
- All the values of graph[u] are unique
- If graph[u] contains v, then graph[v] contains u
Visualization
Tap to expand
Understanding the Visualization
1
Input Graph
Adjacency list representation of undirected graph
2
Color Assignment
Try to color nodes with two colors alternately
3
Bipartite Check
Verify no adjacent nodes have same color
Key Takeaway
🎯 Key Insight: A graph is bipartite if and only if it contains no odd-length cycles
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code