Union-find maintains a partition of items into disjoint groups. It supports asking which group contains an item and merging the groups of two items.
Worked example
When roads open between towns, begin with each town in its own group. For every road, merge the groups of its endpoints. Two towns are connected by the roads seen so far when their representatives match. Path compression and a size- or rank-based union rule keep the structure efficient over a sequence of operations.
What to check
Union-find answers connectivity questions but does not record the route between connected towns. It also does not directly handle arbitrary road removals in its usual form. With path compression and union by rank or size, the standard amortized bound per operation is inverse-Ackermann time, which grows extremely slowly. Check repeated merges and self-connections to ensure they leave the group count consistent.
Continue with the book
Explore the full treatment, worked examples, and exercises in Algorithms Made Simple.
Companion article for Algorithms Made Simple, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
