Sub topic 6
Undirected Graphs: Union-Find
This chapter assumes you can read Python functions and loops. It also assumes you know what an undirected cycle is and how the DFS parent-tracking detector from the previous chapter works. Union-find detects the same cycles in a different way. It never builds an adjacency list or traverses the graph. It reads the edge list one edge at a time.
The Working Model
Union-find, also called a disjoint-set structure, keeps the vertices in groups. Each group is one connected component of the edges seen so far. Every group has a representative vertex, called its root. find(x) returns the root of the group that contains x.
Each edge (u, v) is handled with one test:
- If
uandvhave different roots, the edge joins two separate components. Merge them. - If
uandvhave the same root, a path between them already exists. Adding this edge closes a cycle.
The rule works because a set of edges with no cycle is a forest. In a forest, an edge whose endpoints are already connected is exactly the edge that would create a cycle.
The Code
def has_cycle_union_find(n, edges):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for u, v in edges:
ru, rv = find(u), find(v)
if ru == rv:
return True
parent[ru] = rv
return False
print(has_cycle_union_find(4, [(0, 1), (1, 2), (2, 3), (3, 1)])) # True
print(has_cycle_union_find(4, [(0, 1), (1, 2), (2, 3)])) # FalseThe line parent[x] = parent[parent[x]] does path halving. Each vertex visited during find is pointed at its grandparent, so later lookups follow shorter chains.
A Trace
Here is the first call above, with edges (0,1), (1,2), (2,3), (3,1):
| Edge | find(u) | find(v) | Action | parent after |
|---|---|---|---|---|
| (0,1) | 0 | 1 | merge | [1, 1, 2, 3] |
| (1,2) | 1 | 2 | merge | [1, 2, 2, 3] |
| (2,3) | 2 | 3 | merge | [1, 2, 3, 3] |
| (3,1) | 3 | 3 | cycle | [1, 3, 3, 3] |
During the last find(1), path halving moves vertex 1 from parent 2 to parent 3.
Behavior and Cost
The detector handles several cases without extra code:
- Disconnected graphs: components are tracked implicitly, so no outer loop over start vertices is needed.
- Self-loops:
find(u) == find(u)always holds, so a self-loop is reported as a cycle. - Parallel edges: the second copy of an edge finds both endpoints already joined, so it is reported as a cycle.
With path halving alone, each operation costs O(log n) amortized. If you also merge the smaller tree under the larger one (union by size or rank), the cost drops to O(α(n)) per operation, where α is the inverse Ackermann function. That makes the whole run effectively O(V + E).
Common Errors
- Using it on directed graphs. Union-find ignores direction. For the edges 0→1, 0→2, 1→2 it reports a cycle, but no directed cycle exists. Directed graphs need the methods covered in later chapters.
- Comparing vertices instead of roots. Testing
parent[u] == parent[v]misses connections that run through longer chains. Always comparefind(u)withfind(v).
Exercise
Run hascycleunion_find(5, [(0, 1), (2, 3), (1, 3), (0, 2)]). Which edge triggers the cycle report, and why does the edge before it not trigger one?
Show answer
The edge (0, 2) triggers it. After (0,1), (2,3), and (1,3), all of 0, 1, 2, and 3 are in one set, so find(0) == find(2). The edge (1, 3) does not trigger a report because before it, {0,1} and {2,3} were separate sets with different roots. That edge merges them.
Exercise
An adjacency list for the undirected path 0-1-2 is converted to edges by emitting (u, v) for every neighbor v of every u. What does hascycleunion_find return, and how do you fix it?
Show answer
It returns True, which is wrong, because (1, 0) repeats the edge (0, 1). The fix is to emit an edge only when u < v. That also drops self-loops, so if self-loops matter, use u <= v and make sure each self-loop is stored only once.