Skip to content
Data Structures and Algorithms / Shortest Paths, Spanning Trees, and Weighted Graphs

Union-Find (Disjoint Sets) with Union by Rank and Path Compression

Kruskal's algorithm needs to answer, for every candidate edge, "are these two vertices already in the same connected component?" — the disjoint-set (or union-find) problem: maintain a partition of a universe into disjoint sets, supporting find (which set is xx in?) and union (merge two sets). This note builds the forest-of-trees representation and its two classical optimisations — union by rank and path compression — which together give a running time so close to O(1)O(1) per operation that it is, for any conceivable practical input size, indistinguishable from constant. The precise bound, and its proof, is deferred to the derivation sub-note.

In this lesson

  1. Learning objectives
  2. The disjoint-set ADT
  3. The forest representation
  4. Union by rank
  5. Path compression

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or explore the curriculum.