Sub topic 6
Undirected Graphs: Union-Find
This chapter assumes you can read Python functions and loops, know what an undirected graph is, and have seen the definition of a cycle from earlier in this tutorial. You do not need to know union-find already. The chapter builds it from scratch.
DFS with parent tracking looks at the whole graph at once. Union-find takes a different approach. It reads the edges one at a time and asks a single question about each one: were the two endpoints already connected before this edge arrived? If they were, the new edge closes a cycle.
The Core Idea
Suppose you have processed some edges and none of them formed a cycle. Those edges then form a forest, which is a set of trees. Now edge (u, v) arrives. There are two cases:
uandvare in different trees. Adding the edge joins the two trees into one larger tree. No cycle appears.uandvare already in the same tree. Some pathPalready runs fromutov. Adding(u, v)gives youPplus the new edge, which is a cycle.
So all you need is a structure that tracks which vertices are connected so far and answers "same group?" quickly. A disjoint-set union (DSU), also called union-find, does this. It keeps a partition of the vertices into groups and supports two operations:
find(x)returns a representative vertex (the root) for the group that containsx. Two vertices are in the same group exactly when their roots are equal.union(a, b)merges the groups that containaandb.
How the Structure Works
Each group is stored as a tree of parent pointers in an array. A root points to itself. To find the root of x, you follow parent pointers until you reach a vertex whose parent is itself. To merge two groups, you make one root point to the other.
Here is the minimal version:
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)])) # False
print(has_cycle_union_find(4, [(0, 1), (1, 2), (2, 3), (3, 1)])) # TrueThe line parent[x] = parent[parent[x]] is called path halving. During the walk up to the root, each visited vertex is redirected to its grandparent. This makes later find calls on the same path shorter. Path halving is iterative, so a long chain of parent pointers cannot hit Python's recursion limit.
A Worked Trace
Take 5 vertices and the edges (0,1), (1,2), (3,4), (2,0). The parent array starts as [0, 1, 2, 3, 4].
| Edge | find(u) | find(v) | Action | parent after |
|---|---|---|---|---|
| (0, 1) | 0 | 1 | parent[0] = 1 | [1, 1, 2, 3, 4] |
| (1, 2) | 1 | 2 | parent[1] = 2 | [1, 2, 2, 3, 4] |
| (3, 4) | 3 | 4 | parent[3] = 4 | [1, 2, 2, 4, 4] |
| (2, 0) | 2 | 2 | roots equal, cycle | [2, 2, 2, 4, 4] |
On the last edge, find(0) walks 0 → 1 → 2. Path halving moves parent[0] to 2 on the way. Both roots are 2, so edge (2, 0) closes the cycle 0–1–2–0. The component {3, 4} never interferes, even though it is disconnected from the rest.
Union by Size and Reporting the Offending Edge
The minimal version always attaches ru under rv. In bad edge orders this can still build tall trees. Union by size fixes this by always hanging the smaller tree under the larger one. Together with path halving, it gives amortized O(α(V)) time per operation. α is the inverse Ackermann function, which is at most 4 for any input you could store.
It is also often more useful to return which edge closed the cycle than to return True:
def first_cycle_edge(n, edges):
parent = list(range(n))
size = [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for i, (u, v) in enumerate(edges):
ru, rv = find(u), find(v)
if ru == rv:
return i
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru
size[ru] += size[rv]
return -1
edges = [(0, 1), (1, 2), (3, 4), (2, 0)]
i = first_cycle_edge(5, edges)
print(i, edges[i]) # 3 (2, 0)The returned index is the earliest prefix of the edge list that contains a cycle. That is exactly what you want when edges arrive over time and you need to reject the first bad one.
Arbitrary Vertex Labels and Streaming Edges
Real inputs often use strings or IDs instead of 0..n-1, and you may not know the vertex set ahead of time. A dictionary-backed DSU handles both:
class DisjointSet:
def __init__(self):
self.parent = {}
self.size = {}
def find(self, x):
if x not in self.parent:
self.parent[x] = x
self.size[x] = 1
return x
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
return True
dsu = DisjointSet()
links = [("web", "db"), ("db", "cache"), ("api", "web"), ("cache", "api")]
for a, b in links:
if not dsu.union(a, b):
print("cycle closed by", (a, b)) # cycle closed by ('cache', 'api')
breakHere union returns False when the two endpoints were already connected, which is the cycle signal. This pattern needs no adjacency list and only O(V) memory. That makes it a good fit for streams of edges, and it is the cycle check inside Kruskal's minimum spanning tree algorithm.
Edge Cases Come for Free
The DFS approach needed edge IDs to handle multigraphs correctly. Union-find handles them with no extra code:
| Input | What happens | Correct? |
|---|---|---|
| Self-loop `(u, u)` | `find(u) == find(u)`, reports a cycle | Yes, a self-loop is a cycle of length 1 |
| Parallel edges `(u, v)` twice | First copy merges, second copy finds equal roots | Yes, two parallel edges form a cycle of length 2 |
| Disconnected graph | Each component is its own set; no outer loop needed | Yes |
| Isolated vertices | Never touched; stay as singleton sets | Yes |
If your problem treats the graph as simple (parallel edges should count as one), deduplicate the edges first, for example by normalizing each pair to (min(u, v), max(u, v)) and storing it in a set.
Common Errors
Linking vertices instead of roots
The most frequent bug is writing parent[u] = v instead of parent[find(u)] = find(v). Overwriting parent[u] cuts u loose from whatever it was attached to.
def broken(n, edges):
parent = list(range(n))
def find(x):
while parent[x] != x:
x = parent[x]
return x
for u, v in edges:
if find(u) == find(v):
return True
parent[u] = v # bug: should link roots
return False
print(broken(3, [(0, 1), (0, 2), (1, 2)])) # False, but 0-1-2-0 is a cycleAfter (0, 1), vertex 0 points to 1. Then (0, 2) overwrites parent[0] with 2, so vertex 1 is now alone in its own set. When (1, 2) arrives, the roots differ, and the cycle is missed.
Using it on directed graphs
Union-find ignores edge direction, so it answers "is there an undirected cycle?" For directed edges 0→1, 1→2, 0→2, it reports a cycle at 0→2. The graph is in fact acyclic, since no path leads back to 0. A directed cycle needs a path that follows the arrows, and union-find has no notion of arrows. Directed graphs need three-color DFS or Kahn's algorithm, covered in later chapters.
Expecting deletions
The structure can merge sets but cannot split them. If edges are removed over time, union-find cannot tell you whether a cycle still exists. You would need to rebuild it, or use a fully dynamic connectivity structure, which is much more complex.
When to Choose Union-Find
| Situation | Better choice |
|---|---|
| Edges arrive one at a time; reject the first cycle-forming edge | Union-find |
| You already have an adjacency list and need the cycle's vertices | DFS with parent tracking |
| Edges are sorted and you are building a spanning tree | Union-find (Kruskal) |
| Directed graph | Neither; use three-color DFS or Kahn |
| Edges can be deleted | Neither directly |
Both methods run in near-linear time on a static undirected graph: O(V + E) for DFS and O(V + E·α(V)) for union-find with both optimizations. The real deciding factors are the update pattern and whether you need the cycle itself.
Exercise
Run hascycleunion_find on 6 vertices with edges (0,1), (2,3), (4,5), (1,3), (5,0), (2,4). Which edge triggers the cycle report, and which vertices lie on that cycle?
Show answer
The edge (2,4) triggers it. Before it arrives, the edges (0,1), (2,3), (4,5), (1,3), (5,0) have joined all six vertices into one tree without a cycle. Vertices 2 and 4 already share a root, so (2,4) closes the cycle 2-3-1-0-5-4-2, which contains all six vertices.
Exercise
A colleague uses union-find to check whether a task dependency list (edges "a must run before b") contains a cycle. Give a three-edge input where this reports a false cycle, and explain why.
Show answer
Use a→b, b→c, a→c. Union-find merges a and b, then b and c. At a→c, a and c share a root, so it reports a cycle. Since no directed path returns to a, the dependencies are acyclic. Union-find treats edges as undirected, so a diamond-shaped or triangular DAG looks like a cycle.
Exercise
Why does the minimal version without union by size still produce correct answers, and what does union by size change?
Show answer
Correctness depends only on find returning the same root for vertices in the same set, and on union linking two roots. Both hold no matter which root becomes the parent. Union by size only controls tree height. It keeps trees shallow so that, combined with path halving, each operation costs amortized O(α(V)) and adversarial edge orders cannot cause slowdowns.