Union-Find in Python
Chapter 53: Union-Find
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Groups that merge: find and union
Each group is a small tree with a leader at its root; find(x) follows parent links up to the leader, and union(a, b) hangs one leader under the other.
Union by rank and path compression
Union by rank hangs the shorter tree under the taller one, so trees stay short, and path compression points every item a find passed straight at the leader, so the next find from them takes one step.
Connected components and the redundant connection
Feed every edge to union; each union that merges two groups joins two components, and each union that finds both ends already together is an edge that closes a cycle.
Union-Find or BFS: which to use
Use Union-Find when edges keep arriving and you only ask whether two things are connected (or how many groups there are); use BFS or DFS when you need a path, a distance or an order, or when edges can be removed.