Data Structures · Visualization
Graph: Bipartite Check
Graph
A graph is bipartite if its nodes can be split into two groups such that every edge connects a node in one group to a node in the other — no edge ever connects two nodes within the same group. Time: O(V + E). Space: O(V) for color tracking and traversal.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Bipartite Check
GraphA graph is bipartite if its nodes can be split into two groups such that every edge connects a node in one group to a node in the other — no edge ever connects two nodes within the same group. This is checked by trying to color the graph with just two colors using BFS or DFS: start a node with color 1, give every neighbor color 2, every neighbor of those color 1, and so on; if you ever need to give a node the same color as one of its already-colored neighbors, the graph is not bipartite.
How Bipartite Check Works
- Assign the starting node one of two colors.
- Traverse the graph (BFS or DFS); for each neighbor, assign it the opposite color of the current node.
- If a neighbor is already colored, check that its color is indeed the opposite; if not, the graph is not bipartite.
- Repeat until all nodes are colored or a conflict is found.
Bipartite Check Worked Example
Input: Graph with edges A-B, B-C, C-A (a triangle)
- Color A = 1
- Color B = 2 (opposite of A)
- Color C = 1 (opposite of B)
- Check edge C-A: both are color 1 → conflict!
Output: false (not bipartite — an odd-length cycle exists)
Press ▶ Run to watch it step by step.
def is_bipartite(graph):
color = {} # 0 / 1, unset = absent
for start in graph:
if start in color:
continue
color[start] = 0
stack = [start]
while stack:
v = stack.pop()
for nxt in graph[v]:
if nxt not in color:
color[nxt] = color[v] ^ 1 # opposite
stack.append(nxt)
elif color[nxt] == color[v]:
return False # conflict
return True
# example: bipartiteBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Bipartite Check Time & Space Complexity
When to Use Bipartite Check
- Matching problems, like assigning jobs to applicants or students to schools
- Scheduling problems where two groups must never conflict directly
- Checking two-colorability in map/graph coloring scenarios
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.