Sub topic 2
What Makes a Graph Bipartite
This chapter assumes you know basic graph terms (vertex, edge, path, cycle), can read the adjacency lists from the previous chapter, and can read short Python functions. It defines bipartite graphs, covers the standard examples and non-examples, and looks at the edge cases that most often cause bugs. The next chapters turn the definition into colourings and fast algorithms.
The Definition
A graph G = (V, E) is bipartite if you can split its vertex set V into two disjoint sets L and R so that every edge has one endpoint in L and the other in R. No edge may stay inside L, and no edge may stay inside R.
The pair (L, R) is called a bipartition, and L and R are the two parts (also called sides or classes). Two rules apply:
- L ∪ R = V. Every vertex belongs to some part.
- L ∩ R = ∅. No vertex belongs to both.
The definition is about edges, not vertices. A vertex can have any number of neighbours. All of them must simply lie in the other part.
Many textbooks write a bipartite graph as G = (L, R, E) when the parts are known in advance, as in a graph of students and courses. In other problems you only have G = (V, E), and you have to work out whether a valid split exists. This tutorial is mostly about that second question.
Standard Examples
Some families of graphs are always bipartite. Recognising them saves time and gives you test cases.
| Graph family | Bipartite? | A valid split |
|---|---|---|
| Path with any number of vertices | Yes | Alternate vertices along the path |
| Cycle with an even number of vertices (C4, C6, ...) | Yes | Alternate vertices around the cycle |
| Cycle with an odd number of vertices (C3, C5, ...) | No | None exists |
| Tree or forest | Yes | Even depth versus odd depth from a root |
| Complete bipartite graph K(m, n) | Yes | The m vertices versus the n vertices |
| Grid graph (chessboard adjacency) | Yes | Squares whose row + column is even versus odd |
| Hypercube Q(d) | Yes | Bit strings with an even versus odd number of 1s |
| Complete graph K(n) with n ≥ 3 | No | Any three vertices form a triangle |
| Graph with no edges | Yes | Any split works |
K(m, n) is the complete bipartite graph. It has a part of size m and a part of size n, and every vertex in one part is joined to every vertex in the other. It has m × n edges, the largest number of edges a bipartite graph with those part sizes can have.
The grid and hypercube rows follow one pattern. Every edge changes a parity value (row + column, or the number of 1 bits) by exactly one, so it always joins an even vertex to an odd one. When you can find such a quantity, you have proved the graph is bipartite. Later chapters build on this idea.
Why the Triangle Fails
Take the triangle with vertices 0, 1, 2. Put vertex 0 in L. Edge (0, 1) forces 1 into R. Edge (0, 2) forces 2 into R. Edge (1, 2) now lies inside R. Starting with 0 in R gives the mirror image and fails the same way. No bipartition exists.
Any odd cycle breaks down like this, because going around it switches sides an odd number of times and you cannot end up back where you started. The Odd Cycle Theorem chapter makes this precise and proves the converse. For now, use odd cycles as the quick way to recognise non-bipartite graphs.
Checking a Proposed Bipartition
If someone gives you a split, checking it is simple. Represent the split as a list side where side[v] is 0 for L and 1 for R, then test every edge.
def find_bad_edge(adj, side):
"""side[v] is 0 or 1. Return an edge inside one part, or None if the split is valid."""
for u, neighbours in enumerate(adj):
for v in neighbours:
if side[u] == side[v]:
return (u, v)
return None
square = [[1, 3], [0, 2], [1, 3], [2, 0]]
print(find_bad_edge(square, [0, 1, 0, 1])) # None: valid bipartition
print(find_bad_edge(square, [0, 0, 1, 1])) # (0, 1): both in part 0The check looks at every adjacency entry once, so it takes O(V + E) time. Returning the bad edge instead of just False makes debugging much easier, and it is the same habit the certificate chapter uses later.
Searching for a Bipartition the Slow Way
The definition alone suggests an algorithm: try every split. With n vertices there are 2^n ways to assign each vertex to a part.
from itertools import product
def find_bad_edge(adj, side):
for u, neighbours in enumerate(adj):
for v in neighbours:
if side[u] == side[v]:
return (u, v)
return None
def brute_force_bipartition(adj):
"""Try all 2^n splits. Only usable for very small graphs."""
n = len(adj)
for side in product([0, 1], repeat=n):
if find_bad_edge(adj, side) is None:
return list(side)
return None
square = [[1, 3], [0, 2], [1, 3], [2, 0]]
triangle = [[1, 2], [0, 2], [0, 1]]
loop = [[0]]
print(brute_force_bipartition(square)) # [0, 1, 0, 1]
print(brute_force_bipartition(triangle)) # None
print(brute_force_bipartition(loop)) # None: a self-loop is never bipartiteThis function is correct, and it works well as a reference oracle in randomised tests. It is useless above about 25 vertices. The rest of the tutorial replaces it with a linear-time search that never guesses. The key observation is that placing one vertex forces where all of its neighbours go.
Edge Cases That Break Implementations
The definition is short, but several details catch people out.
Self-Loops
A self-loop is an edge from a vertex to itself. Its two endpoints are the same vertex, so they are in the same part. A graph with a self-loop is never bipartite. A self-loop is a cycle of length 1, and 1 is odd, so this matches the odd-cycle rule. Some code skips v == u while building adjacency lists and silently accepts such graphs. Decide on purpose whether your input can contain loops.
Parallel Edges
Parallel edges (several edges between the same two vertices) make no difference. If one copy of the edge crosses between the parts, every copy does. Two parallel edges do form a cycle of length 2, and 2 is even, which agrees with this.
Graphs With No Edges, or No Vertices
A graph with vertices but no edges is bipartite. Nothing can break the rule, so any split works, including putting every vertex in L. The graph with zero vertices is also bipartite, since the condition holds vacuously. Your code should return a result for it instead of crashing.
Empty Parts
Is a single vertex bipartite? It is if one part may be empty, and most algorithmic sources allow that. Some graph theory texts require both parts to be non-empty. For algorithms, allow empty parts. Otherwise a single isolated vertex becomes a special case for no useful reason.
Directed Graphs
Bipartiteness is defined for undirected graphs. For a directed graph, you normally ignore edge directions and test the underlying undirected graph. If you store only out-edges, the test can miss conflicts. Add each edge in both directions when building the adjacency list.
How Many Bipartitions Are There?
A bipartition is never unique, because you can always swap L and R. That leads to a question that matters when a problem asks you to count or choose between splits.
In a connected bipartite graph, the split is determined up to that swap. Fix one vertex in L, and every vertex at an even distance from it must be in L while every vertex at an odd distance must be in R. Paths leave no other choice.
In a graph with c connected components, each component can be flipped independently of the others. That gives:
- 2^c ordered bipartitions (L, R), where it matters which part is called L.
- 2^(c−1) unordered bipartitions {L, R}, for c ≥ 1.
Isolated vertices count as components. A graph with a single edge plus 3 isolated vertices has c = 4 and so 16 ordered bipartitions. Problems that ask you to "balance the two sides" or "minimise the size of L" depend on this freedom. You solve them by choosing an orientation for each component, which a later chapter on disconnected graphs builds on.
Bipartite Graphs in a Problem Statement
Bipartite structure tends to show up in two forms:
- The two kinds are given. Workers and jobs, students and courses, users and products. Edges only ever join one kind to the other, so the graph is bipartite by construction. You don't test anything. You use the structure, for example in matching.
- The two groups are hidden. "Split these people into two teams so that no two rivals share a team." "Can these exams be held in two time slots without clashes?" Here, edges mean "must be in different groups". The answer is yes exactly when the conflict graph is bipartite, and the split you find is the answer.
The second form is what the coming two-colouring and BFS chapters solve. The first form leads to the matching chapter near the end.
Exercises
Exercise
Is the cycle C6 with one extra edge joining two opposite vertices (vertices 0 and 3 when the cycle is numbered 0 to 5) bipartite? Give a bipartition or explain why none exists.
Show answer
Yes. Use L = {0, 2, 4} and R = {1, 3, 5}. Every cycle edge joins an even vertex to an odd one, and the extra edge (0, 3) joins 0 in L to 3 in R. The chords that would break it are those joining two vertices at even distance around the cycle, such as (0, 2), which creates a triangle 0-1-2.
Exercise
A graph has 10 vertices. Its edges form a path 0-1-2-3 and a separate edge 4-5, and vertices 6, 7, 8 and 9 are isolated. How many ordered bipartitions (L, R) does it have, and how many unordered ones?
Show answer
The components are the path, the edge, and four isolated vertices, so c = 6. There are 2^6 = 64 ordered bipartitions and 2^5 = 32 unordered ones.
Exercise
Someone's adjacency-list builder skips any edge (u, v) with u == v. What wrong answer can this cause, and on which input?
Show answer
It can report that a non-bipartite graph is bipartite. For example, a single vertex with a self-loop, adj = [[0]], has no valid bipartition. With the loop dropped it becomes an isolated vertex, which is bipartite. Either reject self-loops on input or treat them as an immediate "not bipartite".
Exercise
Explain why every grid graph, where cell (r, c) is adjacent to the cells directly above, below, left and right of it, is bipartite.
Show answer
Each edge changes either r or c by exactly 1, so it changes the parity of r + c. Put cells with even r + c in L and cells with odd r + c in R. Every edge then joins an even cell to an odd cell, which is the colouring of a chessboard.