Sub topic 3
Two-Colouring: Bipartiteness as a Colouring Problem
This chapter assumes you know basic graph terms (vertex, edge, path, cycle), can read a graph stored as Python adjacency lists, and are comfortable with Big-O notation. The previous chapter defined a bipartite graph as one whose vertices split into two sides, with every edge crossing between them. This chapter restates that definition as a colouring problem. The colouring version is the one that algorithms actually check.
From Two Sides to Two Colours
A colouring of a graph assigns a label, called a colour, to each vertex. A colouring is proper if no edge joins two vertices of the same colour. A proper two-colouring uses only two colours, written here as 0 and 1.
A bipartition and a proper two-colouring describe the same structure:
- Given a bipartition
(L, R), colour every vertex inLwith0and every vertex inRwith1. Every edge crosses fromLtoR, so every edge has endpoints of different colours. - Given a proper two-colouring, let
Lbe the vertices coloured0andRthe vertices coloured1. No edge stays inside one colour class, so every edge crosses betweenLandR.
So a graph is bipartite exactly when it has a proper two-colouring. The two definitions are one idea in two vocabularies. Code works more easily with colours because a colour is a single integer per vertex, stored in an array indexed by vertex.
def partition_to_colouring(n, left):
"""Turn a bipartition (given by its left side) into a colour list."""
left = set(left)
return [0 if v in left else 1 for v in range(n)]
def colouring_to_partition(colour):
"""Turn a colour list into the two sides of a bipartition."""
left = [v for v, c in enumerate(colour) if c == 0]
right = [v for v, c in enumerate(colour) if c == 1]
return left, right
print(partition_to_colouring(4, [0, 2])) # [0, 1, 0, 1]
print(colouring_to_partition([0, 1, 0, 1])) # ([0, 2], [1, 3])Verifying a Colouring
Checking whether a given colouring is proper is easy. Look at every edge and compare its endpoints' colours. Finding a colouring is a separate problem, which later chapters solve. A checker is still worth writing first, because you can use it to test every colouring algorithm you build.
def is_proper_two_colouring(n, adj, colour):
"""Return True if colour is a proper two-colouring of the graph."""
if len(colour) != n:
return False
if any(c not in (0, 1) for c in colour):
return False
for u in range(n):
for v in adj[u]:
if colour[u] == colour[v]:
return False
return True
square = [[1, 3], [0, 2], [1, 3], [2, 0]]
print(is_proper_two_colouring(4, square, [0, 1, 0, 1])) # True
print(is_proper_two_colouring(4, square, [0, 0, 1, 1])) # False: edge 0-1The checker visits each adjacency list once. An undirected edge appears in two lists, so the loop body runs 2E times, and the whole check costs O(V + E). The check also handles a self-loop, an edge from a vertex to itself. If u appears in adj[u], the test colour[u] == colour[u] is true, and the function correctly rejects the colouring. A graph with a self-loop is never bipartite.
The Edge Constraint as Parity
Each edge (u, v) imposes the constraint
colour[u] XOR colour[v] = 1
or, written in arithmetic modulo 2, colour[u] + colour[v] ≡ 1 (mod 2). A proper two-colouring is a solution to a system of these equations, one per edge.
This view gives you a useful rule for reasoning about colourings. Walk along a path v0, v1, ..., vk. Each step flips the colour, so after k steps
colour[vk] = colour[v0] XOR (k mod 2).
Every step along an edge flips the colour, so a vertex at an even number of steps from v0 has the same colour as v0, and a vertex at an odd number of steps has the opposite colour.
Two consequences follow directly:
- Colours are forced. Once you fix the colour of one vertex, every vertex reachable from it has its colour determined by the parity of the path length.
- Different paths must agree. If two paths from
v0towhave lengths of different parity, they demand opposite colours forw, and no proper two-colouring exists. Joining two such paths produces a closed walk of odd length. The next chapter turns this observation into the odd cycle theorem.
The parity view comes back in the chapter on parity union-find, which stores exactly these XOR relationships between vertices.
How Many Two-Colourings Does a Graph Have?
Forcing means a connected graph, one where every vertex is reachable from every other, has very little freedom. Choose the colour of any one vertex. Every other colour then follows. Choosing 0 or 1 for that first vertex gives two colourings, and one is the other with the colours swapped. A connected bipartite graph therefore has exactly 2 proper two-colourings, and its bipartition is unique up to swapping the sides.
A graph made of c separate pieces, called connected components, lets you choose independently in each piece. A bipartite graph with c components has exactly 2^c proper two-colourings. A graph with no proper two-colouring has 0.
You can confirm this on small graphs by brute force. The code below tries all 2^n colour assignments. That is exponential, so use it only to test intuition.
from itertools import product
def is_proper_two_colouring(n, adj, colour):
for u in range(n):
for v in adj[u]:
if colour[u] == colour[v]:
return False
return True
def count_two_colourings(n, adj):
"""Count proper two-colourings by trying all 2**n assignments."""
return sum(
is_proper_two_colouring(n, adj, list(c))
for c in product((0, 1), repeat=n)
)
square = [[1, 3], [0, 2], [1, 3], [2, 0]]
triangle = [[1, 2], [0, 2], [0, 1]]
two_edges = [[1], [0], [3], [2]] # 0-1 and 2-3, two components
no_edges = [[], [], []] # three isolated vertices
print(count_two_colourings(4, square)) # 2
print(count_two_colourings(3, triangle)) # 0
print(count_two_colourings(4, two_edges)) # 4
print(count_two_colourings(3, no_edges)) # 8The results match the formula. The square is connected, so it has 2^1 = 2 colourings. The triangle has none. Two disjoint edges form 2 components and give 2^2 = 4. Three isolated vertices form 3 components and give 2^3 = 8. An isolated vertex has no constraints, so either colour works.
Common Two-Colourable Families
Recognising these families saves you from running an algorithm when the structure already answers the question.
| Graph family | Two-colourable? | A proper colouring |
|---|---|---|
| Path with any number of vertices | Yes | Alternate 0, 1, 0, 1 along the path |
| Even cycle (4, 6, 8, ... vertices) | Yes | Alternate around the cycle |
| Odd cycle (3, 5, 7, ... vertices) | No | Alternating returns to the start with the wrong colour |
| Tree | Yes | Colour by depth parity from any root |
| Grid graph (rows × columns) | Yes | `(row + col) % 2`, like a chessboard |
| Hypercube on bit strings | Yes | Parity of the number of 1 bits |
| Complete graph on 3 or more vertices | No | Contains a triangle |
| Complete bipartite graph K(m, n) | Yes | One side 0, the other side 1 |
The grid and hypercube entries follow the same pattern. Each edge changes a quantity by exactly one, either the sum row + col or the count of 1 bits, so its parity flips on every edge. If you can find a quantity whose parity flips along every edge, you have found a two-colouring.
def grid_adjacency(rows, cols):
"""Build adjacency lists for a rows x cols grid graph."""
def idx(r, c):
return r * cols + c
adj = [[] for _ in range(rows * cols)]
for r in range(rows):
for c in range(cols):
if r + 1 < rows:
adj[idx(r, c)].append(idx(r + 1, c))
adj[idx(r + 1, c)].append(idx(r, c))
if c + 1 < cols:
adj[idx(r, c)].append(idx(r, c + 1))
adj[idx(r, c + 1)].append(idx(r, c))
return adj
def is_proper_two_colouring(n, adj, colour):
return all(colour[u] != colour[v] for u in range(n) for v in adj[u])
rows, cols = 3, 4
adj = grid_adjacency(rows, cols)
chessboard = [(r + c) % 2 for r in range(rows) for c in range(cols)]
print(is_proper_two_colouring(rows * cols, adj, chessboard)) # TrueCommon Errors
These errors cause most wrong answers in two-colouring code.
| Error | What goes wrong | Fix |
|---|---|---|
| Treating a directed graph as given | An edge stored only as `u -> v` is checked from `u`'s list but never from `v`'s list | Bipartiteness ignores direction. Add both `adj[u].append(v)` and `adj[v].append(u)` |
| Ignoring self-loops | Some hand-written checks skip `u == v` | A self-loop makes the graph non-bipartite. Keep the comparison |
| Using a third value as a colour | An "uncoloured" marker such as `-1` slips into the final answer | Verify that every value is in `{0, 1}` before accepting the colouring |
| Assuming the colouring is unique | Tests compare against one expected list and fail on the swapped version | Compare bipartitions up to swap, or test with a checker |
| Fixing only one vertex's colour in a disconnected graph | Vertices in other components never receive a colour | Start a new colouring in every component (covered in a later chapter) |
Exercises
Exercise
A connected bipartite graph has 10 vertices. How many proper two-colourings does it have, and why does the number not depend on the edges?
Show answer
Exactly 2. In a connected graph, fixing one vertex's colour forces every other colour through path parity. The only free choice is that first vertex's colour, 0 or 1. Adding or removing edges changes which colourings are proper, but it cannot add freedom while the graph stays connected and bipartite.
Exercise
A graph has 7 vertices and the edges 0-1, 1-2, 3-4 and 5-5. How many proper two-colourings does it have?
Show answer
0. The edge 5-5 is a self-loop, so vertex 5 would need a colour different from its own. Without that self-loop the graph would have 4 components ({0,1,2}, {3,4}, {5}, {6}) and 2^4 = 16 colourings.
Exercise
Using the parity rule, explain why a cycle with 5 vertices has no proper two-colouring.
Show answer
Start at vertex v0 with colour 0 and walk around the cycle. Each of the 5 steps flips the colour, so on returning to v0 the colour is 0 XOR (5 mod 2) = 1. That contradicts v0's colour of 0, so no proper two-colouring exists.
Exercise
The vertices of a graph are the integers 0 to 99. Two integers are joined when they differ by exactly 3 or exactly 5. Is the graph two-colourable? Give a colouring or explain why none exists.
Show answer
Yes. Colour each integer x with x % 2. Every edge joins numbers that differ by an odd amount (3 or 5), so the endpoints always have opposite parity. This is the "quantity whose parity flips on every edge" pattern.