Sub topic 9
Proving a Graph Is Not Bipartite: Finding an Odd Cycle
This chapter assumes you already know the BFS two-colouring algorithm from earlier chapters, the odd cycle theorem (a graph is bipartite exactly when it has no odd cycle), and how BFS builds a tree of parent pointers. You should be comfortable reading Python and reasoning about BFS depths.
So far the two-colouring routine answers "not bipartite" by returning None. That answer is correct, but nobody can check it without rerunning the whole algorithm. This chapter shows how to return an odd cycle instead. An odd cycle is a closed path with an odd number of edges, and it serves as a certificate: a small piece of evidence that anyone can check quickly and independently.
Why a Certificate Matters
A yes/no answer asks the caller to trust your code. A certificate removes that trust requirement. Bipartiteness has a certificate in both directions.
| Answer | Certificate | How to check it | Cost to check |
|---|---|---|---|
| Bipartite | A colour for every vertex | Every edge joins different colours | O(V + E) |
| Not bipartite | An odd cycle | Consecutive vertices are adjacent, length is odd, no repeats | O(L) with adjacency sets, where L is the cycle length |
The odd cycle theorem guarantees that one of these two certificates always exists. A program that returns one or the other can therefore be checked on every run. Certificates are useful in practice:
- When a scheduling or conflict-splitting model is infeasible, the odd cycle names the exact constraints that clash. For example: "Alice, Bob, and Carol all conflict pairwise."
- In tests, you can verify the output without a reference implementation.
- In debugging, a short cycle tells you which edges in your input are wrong.
The Key Fact: Conflicts Happen at Equal Depth
BFS assigns each vertex a depth, which is its distance in edges from the start vertex of its component. In BFS two-colouring, a vertex's colour equals its depth mod 2.
BFS also has a structural property: every edge joins vertices whose depths differ by at most 1. If an edge joined depth d to depth d + 2 or deeper, BFS would have discovered the deeper vertex from the shallower one at depth d + 1.
Combine the two facts. A conflict edge (u, v) has colour[u] == colour[v], so the two depths have the same parity. They also differ by at most 1. Two integers with the same parity that differ by at most 1 must be equal. So u and v sit at the same depth k.
Follow parent pointers up from u and from v at the same time. Because both start at depth k, both pointers reach each depth level together, and they first meet at the lowest common ancestor (LCA). Say the LCA is at depth k − j. Then:
- the tree path from u to the LCA has j edges,
- the tree path from v to the LCA has j edges,
- the conflict edge (u, v) adds 1 edge.
The cycle has length 2j + 1, which is odd. The two tree paths share no vertex except the LCA, because they first meet there. The cycle is therefore simple: no vertex repeats.
BFS Implementation
The code below extends BFS two-colouring with parent and depth arrays. When it finds a conflict, it walks both endpoints up in lockstep and stitches the two paths together.
from collections import deque
def find_odd_cycle(n, adj):
"""Return a list of vertices forming an odd cycle, or None if bipartite."""
colour = [-1] * n
parent = [-1] * n
depth = [0] * n
for s in range(n):
if colour[s] != -1:
continue
colour[s] = 0
queue = deque([s])
while queue:
u = queue.popleft()
for v in adj[u]:
if colour[v] == -1:
colour[v] = 1 - colour[u]
parent[v] = u
depth[v] = depth[u] + 1
queue.append(v)
elif colour[v] == colour[u]:
# u and v have equal BFS depth; walk both up to their common ancestor.
path_u, path_v = [u], [v]
a, b = u, v
while a != b:
a = parent[a]
b = parent[b]
path_u.append(a)
path_v.append(b)
# path_u: u .. ancestor, then back down to v; edge (v, u) closes the cycle.
return path_u + path_v[-2::-1]
return None
triangle = [[1, 2], [0, 2], [0, 1]]
pentagon = [[1, 4], [0, 2], [1, 3], [2, 4], [3, 0]]
print(find_odd_cycle(3, triangle)) # [1, 0, 2]
print(find_odd_cycle(5, pentagon)) # [2, 1, 0, 4, 3]Here is how the cycle is assembled. path_u runs from u up to the ancestor. path_v[-2::-1] runs from just below the ancestor back down to v, which skips the ancestor so it is not listed twice. The final edge, from v back to u, is the conflict edge itself. Its endpoints are the last and first entries of the list.
Here is a trace on the pentagon. BFS from 0 gives depth 1 to vertices 1 and 4, then depth 2 to vertex 2 (from 1) and vertex 3 (from 4). Processing vertex 2 finds neighbour 3 with the same colour. The walk-up gives path_u = [2, 1, 0] and path_v = [3, 4, 0], and the result is [2, 1, 0, 4, 3].
The extra work is small. Building the cycle takes O(k) steps for a conflict at depth k, and the algorithm stops at the first conflict, so total time stays O(V + E).
Verifying the Certificate
A certificate only helps if checking it is cheap and independent of the code that produced it. This verifier makes no use of colours or BFS:
def is_odd_cycle(adj, cycle):
"""Check that cycle is a simple cycle of odd length in the graph."""
if not cycle or len(cycle) % 2 == 0:
return False
if len(set(cycle)) != len(cycle):
return False
neighbours = [set(nbrs) for nbrs in adj]
for i, u in enumerate(cycle):
v = cycle[(i + 1) % len(cycle)]
if v not in neighbours[u]:
return False
return True
pentagon = [[1, 4], [0, 2], [1, 3], [2, 4], [3, 0]]
print(is_odd_cycle(pentagon, [2, 1, 0, 4, 3])) # True
print(is_odd_cycle(pentagon, [0, 1, 2, 3])) # False: even length, and 3-0 is not an edgeBuilding the neighbour sets costs O(V + E). If you keep sets as your adjacency structure from the start, the check costs O(L). In a test suite, pair this with a check that a returned colouring is proper, and you can fuzz the algorithm on random graphs with no reference answer.
Gotcha: Lockstep Walking Only Works with BFS
The proof that both endpoints sit at equal depth relies on a BFS property. With DFS, or the stack-based traversal from the previous chapter, a conflict edge can join vertices at depths 2 and 6. If you walk those up in lockstep, the two pointers never meet at the same moment. The loop then runs past the root, and parent[-1] silently indexes the last element of the list.
The fix works for any traversal in which colour equals tree depth mod 2. That property holds whenever each newly coloured vertex gets depth[parent] + 1 and the opposite colour. Lift the deeper endpoint first, then walk up in lockstep. The cycle length is (du − a) + (dv − a) + 1, where a is the LCA depth. Because du and dv have the same parity, the first two terms sum to an even number, and the total is odd.
def cycle_from_conflict(u, v, parent, depth):
"""Build an odd cycle from a same-colour edge (u, v) in any traversal tree."""
path_u, path_v = [u], [v]
a, b = u, v
while depth[a] > depth[b]:
a = parent[a]
path_u.append(a)
while depth[b] > depth[a]:
b = parent[b]
path_v.append(b)
while a != b:
a = parent[a]
b = parent[b]
path_u.append(a)
path_v.append(b)
return path_u + path_v[-2::-1]
def find_odd_cycle_dfs(n, adj):
"""Stack-based traversal that returns an odd cycle or None."""
colour = [-1] * n
parent = [-1] * n
depth = [0] * n
for s in range(n):
if colour[s] != -1:
continue
colour[s] = 0
stack = [s]
while stack:
u = stack.pop()
for v in adj[u]:
if colour[v] == -1:
colour[v] = 1 - colour[u]
parent[v] = u
depth[v] = depth[u] + 1
stack.append(v)
elif colour[v] == colour[u]:
return cycle_from_conflict(u, v, parent, depth)
return None
pentagon = [[1, 4], [0, 2], [1, 3], [2, 4], [3, 0]]
print(find_odd_cycle_dfs(5, pentagon)) # [3, 2, 1, 0, 4]Edge Cases
- Self-loops. An edge (u, u) is a cycle of length 1. The conflict test fires with u == v, the walk-up loops do nothing, and both functions return
[u]. The verifier accepts it, because u is in its own neighbour set. - Parallel edges. Two edges between the same pair form a cycle of length 2, which is even. They never cause a conflict, so no special handling is needed.
- Disconnected graphs. The
parentanddeptharrays are per vertex, and each component's tree ends at its own root. Both endpoints of a conflict edge lie in the same component, so their LCA always exists. - Directed input. If
adjlists only one direction of each edge, BFS can miss conflicts or build the wrong trees. Symmetrise the adjacency lists before you test bipartiteness.
The Cycle Found Is Not Necessarily the Shortest
BFS returns the first odd cycle it closes, and that cycle depends on the start vertex and the order of the adjacency lists. It is always simple, but it may be longer than necessary. Suppose a long odd ring has a triangle attached far from the start vertex. The search may close the ring before it reaches the triangle.
| Goal | Method | Time |
|---|---|---|
| Any odd cycle | One BFS pass, stop at the first conflict | O(V + E) |
| Shortest odd cycle | BFS from every vertex, take the smallest 2j + 1 | O(V · (V + E)) |
Exercise
In BFS two-colouring, a conflict edge (u, v) is found with depth[u] = 7. What are the possible values of depth[v], and what are the possible lengths of the extracted cycle?
Show answer
depth[v] must be 7, because the depths have the same parity (same colour) and differ by at most 1 (BFS edge property). If the lowest common ancestor is at depth 7 − j for some j from 1 to 7, the cycle length is 2j + 1, so it is one of 3, 5, 7, 9, 11, 13, 15.
Exercise
Someone runs the original lockstep findoddcycle code, unchanged except that deque.popleft is replaced by list.pop (making it stack-based). Explain what can go wrong and give the fix.
Show answer
With a stack, a conflict edge can join vertices at different depths that have the same parity, such as 2 and 4. Lockstep walking then never makes a equal b at the same step. The pointers pass the root and reach parent value -1, which Python treats as the last list index, so the output is garbage or the loop never ends. The fix is to first lift the deeper endpoint until both depths match, then walk in lockstep, as cyclefromconflict does.
Exercise
Write the cycle returned by findoddcycle for the graph with adjacency lists [[1], [0, 2, 3], [1, 3], [1, 2]] and check it with isoddcycle.
Show answer
BFS from 0 colours 1 at depth 1. Processing 1 colours 2 and 3 at depth 2, both with parent 1. Processing 2 finds neighbour 3 with the same colour. The walk-up gives pathu = [2, 1] and pathv = [3, 1], so the result is [2, 1, 3]. That list has odd length and no repeats, and 2-1, 1-3 and 3-2 are all edges, so isoddcycle returns True.