Sub topic 11
Checking Bipartiteness as Edges Arrive with Parity Union-Find
This chapter assumes you have read the earlier chapters on two-colouring and connected components, and that you know the basic union-find (disjoint set union) structure, which supports find and union with path compression. You should also be comfortable with XOR on bits.
The problem: edges that arrive one at a time
The BFS and DFS tests from earlier chapters take a finished graph and answer once. Sometimes the graph is not finished. Edges arrive in a stream, and after each one you must say whether the graph so far is still bipartite. Some typical cases:
- A scheduler receives "these two jobs must run on different machines" constraints one by one and must reject the first constraint that makes a two-machine split impossible.
- A puzzle checker receives "cell A and cell B differ" clues and must flag the first contradiction.
- A judge problem gives you E edges and asks for the index of the first edge after which the graph stops being bipartite.
Rerunning BFS after every insertion costs O(V + E) per edge, so O(E · (V + E)) in total. With a million edges that will not finish. A parity union-find answers each insertion in near-constant amortised time.
Why insertions alone keep things simple
Adding an edge can only add cycles. It never removes one. So once the graph contains an odd cycle, it keeps that cycle forever, and bipartiteness is a monotone property under insertion: it holds for a prefix of the stream and then fails for good. This is why a structure that only supports merging, like union-find, fits the problem.
The working model: colours relative to a root
Within one connected component, a proper two-colouring is fixed once you pick the colour of any single vertex. Flip that choice and every colour in the component flips. So the absolute colour does not matter. What matters is whether two vertices have the same or different colours.
Union-find already groups vertices into components, each with a representative root. We add one bit per vertex:
parity[x]is 0 ifxhas the same colour as its parent in the union-find tree, and 1 if it has the opposite colour.
The colour of x relative to its root is the XOR of the parity bits along the path from x up to the root. Path compression has to keep that value correct when it rewires x to point straight at the root.
When an edge (u, v) arrives, find both roots and both relative colours pu and pv:
| Situation | Meaning | Action |
|---|---|---|
| Different roots | u and v are in separate components | Merge, choosing the root's parity so u and v end up different |
| Same root, `pu != pv` | Edge joins opposite colours | Nothing to change; still bipartite |
| Same root, `pu == pv` | Edge joins equal colours, closing an odd cycle | Report failure |
The core implementation
class ParityDSU:
"""Union-find where parity[x] is x's colour relative to its parent."""
def __init__(self, n):
self.parent = list(range(n))
self.parity = [0] * n
def find(self, x):
if self.parent[x] == x:
return x, 0
root, p = self.find(self.parent[x])
self.parity[x] ^= p # now relative to root
self.parent[x] = root # path compression
return root, self.parity[x]
def add_edge(self, u, v):
"""Record that u and v must differ; return False if this breaks bipartiteness."""
ru, pu = self.find(u)
rv, pv = self.find(v)
if ru == rv:
return pu != pv
self.parent[ru] = rv
self.parity[ru] = pu ^ pv ^ 1
return True
dsu = ParityDSU(3)
print(dsu.add_edge(0, 1)) # True
print(dsu.add_edge(1, 2)) # True
print(dsu.add_edge(2, 0)) # False: closes a triangleWhy the merge parity is `pu ^ pv ^ 1`
After parent[ru] = rv, the colour of u relative to rv is pu ^ parity[ru]: first from u up to ru, then from ru up to rv. We need that to differ from pv, the colour of v relative to rv, so it must equal pv ^ 1. Solving pu ^ parity[ru] = pv ^ 1 gives parity[ru] = pu ^ pv ^ 1. The formula is symmetric in u and v, so the same value works if you attach rv under ru instead. Union by size depends on that symmetry.
Why `find` updates parity before rewiring
In the recursive call, p is the colour of parent[x] relative to the root. Before compression, parity[x] is relative to the old parent. XOR-ing the two gives the colour relative to the root, and only after that is it safe to set parent[x] = root. If you swap those two lines, the code still runs but stores parities relative to the wrong vertex. The answers it gives will be silently wrong.
A traced example
Insert the edges (0,1), (2,3), (1,2), (3,0), (0,2) on four vertices.
| Edge | find results | Action | Result |
|---|---|---|---|
| (0,1) | (0,0), (1,0) | parent[0]=1, parity[0]=1 | True |
| (2,3) | (2,0), (3,0) | parent[2]=3, parity[2]=1 | True |
| (1,2) | (1,0), (3,1) | parent[1]=3, parity[1]=0 | True |
| (3,0) | (3,0), (3,1) | same root, 0 ≠ 1 | True: 4-cycle 0-1-2-3 is even |
| (0,2) | (3,1), (3,1) | same root, 1 = 1 | False: triangle 0-1-2 |
During the fourth step, find(0) walks 0 → 1 → 3. It compresses 0 to point at 3 and sets parity[0] = 1 ^ 0 = 1, which means vertex 0 has the opposite colour to vertex 3. That matches the 4-cycle, where 0 and 3 are adjacent.
Gotchas and a hardened version
Recursion depth
The core class has no union by rank or size. An adversarial stream such as (0,1), (1,2), (2,3), … can build a chain of length n before any compression happens. The first find on the deepest vertex then recurses n levels. Python's default recursion limit is about 1000, so the core class will crash on large inputs. The fix is an iterative find plus union by size, which keeps trees at O(log n) height even before compression.
class ParityDSU:
"""Iterative parity union-find with union by size and path compression."""
def __init__(self, n):
self.parent = list(range(n))
self.parity = [0] * n
self.size = [1] * n
def find(self, x):
path = []
while self.parent[x] != x:
path.append(x)
x = self.parent[x]
root = x
acc = 0
# Walk from the node nearest the root back down to the original x.
for node in reversed(path):
acc ^= self.parity[node]
self.parity[node] = acc
self.parent[node] = root
return root, acc
def add_edge(self, u, v):
ru, pu = self.find(u)
rv, pv = self.find(v)
if ru == rv:
return pu != pv
if self.size[ru] > self.size[rv]:
ru, rv = rv, ru
self.parent[ru] = rv
self.parity[ru] = pu ^ pv ^ 1
self.size[rv] += self.size[ru]
return True
def colour(self, x):
return self.find(x)[1]
def first_breaking_edge(n, edges):
"""Return the index of the first edge that makes the graph non-bipartite, or -1."""
dsu = ParityDSU(n)
for i, (u, v) in enumerate(edges):
if not dsu.add_edge(u, v):
return i
return -1
edges = [(0, 1), (2, 3), (1, 2), (3, 0), (0, 2)]
print(first_breaking_edge(4, edges)) # 4
chain = [(i, i + 1) for i in range(200000)]
print(first_breaking_edge(200001, chain)) # -1, no recursion error
dsu = ParityDSU(4)
for u, v in edges[:4]:
dsu.add_edge(u, v)
print([dsu.colour(x) for x in range(4)]) # [1, 0, 1, 0], a valid colouringIn the iterative find, acc builds each node's parity relative to the root, starting from the node closest to the root. The parent's value is already folded into acc before the child is processed, so the order of the loop matters.
Self-loops and duplicate edges
A self-loop (u, u) is a cycle of length 1, which is odd. add_edge(u, u) finds the same root and the same parity twice, so it returns False, which is correct. A duplicate edge (u, v) arriving a second time finds pu != pv and returns True without changing anything, which is also correct.
Failure leaves the structure unchanged
When add_edge returns False it modifies nothing, apart from harmless path compression. You can choose to ignore the bad edge and keep going, which answers the question "accept each constraint only if it stays consistent with the ones accepted so far." If you keep inserting edges after a failure without that policy, the structure no longer describes the real graph.
Cost and comparison
With path compression and union by size, a sequence of m operations costs O(m α(n)), where α is the inverse Ackermann function. α(n) is at most 4 for any input you will ever see. Space is O(V): three arrays. The structure never stores the edges, which makes it useful when the stream is too large to keep.
| Approach | Per insertion | Total for E edges | Gives an odd cycle? | Supports deletion? |
|---|---|---|---|---|
| Rerun BFS each time | O(V + E) | O(E(V + E)) | Yes | Yes, by rerunning |
| BFS once at the end | none | O(V + E) | Yes | Not applicable |
| Parity union-find | O(α(V)) amortised | O(E α(V)) | No | No |
If you only need a single answer for a finished graph, BFS is simpler and also gives you the odd-cycle certificate from the previous chapter. Use the parity union-find when you need an answer after every insertion, when you need the first edge that breaks bipartiteness, or when you cannot store the edges.
Generalising to "same" and "different" constraints
Change the merge parity from pu ^ pv ^ 1 to pu ^ pv ^ d, where d = 1 means "must differ" and d = 0 means "must match". The same structure then checks any system of equations of the form colour(u) XOR colour(v) = d. This is a linear system over GF(2) in which each equation has two variables. Many puzzle and constraint problems reduce to it.
Exercise
Using the core ParityDSU on 5 vertices, insert (0,1), (1,2), (3,4), (2,3). Then call add_edge(0,4). Does it return True or False, and what cycle (if any) is involved?
Show answer
It returns True. The edges form the path 0-1-2-3-4, so the colours alternate 0,1,0,1,0 along the path, and vertices 0 and 4 have the same colour. That sounds like a conflict, but the edge (0,4) closes the cycle 0-1-2-3-4-0, which has length 5. Check the parities directly: 0 and 4 are at even distance along the path, so pu == pv, and add_edge returns False. The correct answer is False, because the 5-cycle is odd.
Exercise
Why must find XOR the parent's root-relative parity into parity[x] before setting parent[x] = root, and what goes wrong if you instead set parity[x] = p?
Show answer
parity[x] is stored relative to x's old parent, and p is the parent's parity relative to the root. x's parity relative to the root is the XOR of the two. Setting parity[x] = p throws away the x-to-parent bit, so x would get its parent's colour. Every edge that passes through a compressed path would then be judged with a wrong colour.
Exercise
Modify add_edge to take a third argument d (0 for "u and v must have the same colour", 1 for "must differ"). What is the condition for returning False when ru == rv, and what is the merge parity?
Show answer
When the roots are equal, return (pu ^ pv) == d, which means returning False exactly when pu ^ pv != d. When merging, set parity[ru] = pu ^ pv ^ d. With d = 1 this reduces to the original add_edge.
Exercise
A stream contains 10^6 edge insertions interleaved with 10^5 deletions, and after each operation you must report whether the graph is bipartite. Is the parity union-find from this chapter enough?
Show answer
No. Union-find cannot undo a merge, so a deletion that splits a component cannot be represented. Either rerun a linear-time BFS after each deletion, which is too slow here, or use offline dynamic connectivity: a segment tree over time with a rollback parity union-find that uses union by size and no path compression.