Disjoint Sets

Sixteen people join groups in 31 operations. A plain forest of parent pointers follows 89 pointers to answer them. Two small rules, union by rank and path compression, cut that to 27: less than one pointer per operation.

Pick a strategy and drag the operations. Watch the tallest tree and the four cost bars. Then we build, piece by piece, the three operations, the forest, the two rules, and why the cost per operation stays near one.

You need a little Python and the idea of a tree (nodes joined by parent links). Amortized analysis helps but is not required. We build the rest from zero.

Based on Chapter 21, Data Structures for Disjoint Sets, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: van Emde Boas Trees. Next: Elementary Graph Algorithms.

Run one workload four ways

31

Illustrative workload: people 0 to 7 merge in pairs, then quads, then one group of eight. Then people 8 to 15 join one at a time, and after each join we look up two random members. A hop is one parent pointer followed.

Chapter 0

The Friend Groups

See a fresh search pay for the whole network on every question, and meet the structure that remembers

You run a small social network. Friendships arrive one at a time. All day, people ask one question: "Are Ana and Ben in the same friend group?" Same group means a chain of friendships links them, of any length.

The obvious answer is a fresh search. Start at Ana, follow every friendship outward with a breadth-first search (visit all neighbours, then their neighbours), and stop if you reach Ben. It is correct. But it forgets everything after each question, so the next question pays again.

Add friendships, ask questions

200 people. Drag the number of friendships. Each bar is the average work for one question, over 50 random pairs. The axis is logarithmic.

300

Illustrative: random friendships between 200 people, seeded. Search work counts people visited plus friendships scanned. Union-find work counts parent pointers followed plus one comparison.

With 300 friendships, the fresh search does about 244 steps per question. The structure of this chapter answers the same question in about 3. And as friendships grow, its cost barely moves.

That structure keeps the people in disjoint sets: groups where no person is in two groups. When a friendship joins two groups, it merges them. When someone asks, it checks if two people sit in the same group. It never stores the chain of friends, only the grouping. People also call it union-find.

The failure. Symptom: a "same group?" check slows down as the network grows. Measure: time 1,000 questions at 10,000 and at 20,000 friendships; if the time doubles, each question scans the network. Fix: keep the groups up to date as friendships arrive, so a question costs a few pointer steps.

The road

  1. Three operations: MakeSet, Find, Union, and what they promise.
  2. Linked lists: fast Find, slow Union, and the weighted union.
  3. The forest: one array of parent pointers. The hero's trees.
  4. Union by rank: the hero's "By rank" button.
  5. Path compression: the hero's "Compress" button.
  6. Both tricks together: the hero's bars, at every size (the showcase).
  7. The inverse Ackermann function: why the cost stays near constant.
  8. Kruskal and cycle checks: union-find inside a graph algorithm.
  9. Percolation: when does water get through?
  10. The field guide: terms, numbers, code and the credit.
Edges of a graph arrive one at a time. Between arrivals you must answer "are u and v connected?" Which plan fits best?

Chapter 1

Three Operations

Name each set by one of its members, and define the whole structure with three calls

Six people, numbered 0 to 5, start alone. How do we name a group? Each set picks one member as its representative. Two people are in the same set exactly when their sets have the same representative. Which member it is does not matter, if it stays the same while the set does not change.

The whole structure is three operations:

  1. MakeSet(x) makes a new set that holds only x. Its representative is x.
  2. Find(x) returns the representative of the set that holds x.
  3. Union(x, y) merges the set of x and the set of y into one set.

"Are x and y together?" is then one line: Find(x) == Find(y).

Step through the script

Each box is one set. The warm ring marks its representative. Press Next to run the script one line at a time.

The script: Union(0, 1), Union(2, 3), two questions, Union(0, 3), two more questions.

Look at the last questions. We never joined 0 and 2 directly. Union(0, 1), Union(2, 3) and Union(0, 3) put them together anyway. The structure handles this chain of links for you: if a is with b and b is with c, then a is with c.

Count the cost in a real run. With n people and m operations in total, n of the m are MakeSet calls. At most n − 1 Unions can do anything, because each real merge removes one set. CLRS states every bound in this chapter with these two numbers, n and m.

The failure. Symptom: two people show as separate after a merge that should join them. Measure: print Find for both; if the representatives differ, the code merged the wrong sets. Fix: Union must find both representatives first, then link those, never the two people themselves.

After Union(0, 1), Union(2, 3) and Union(1, 2), what does Find(0) == Find(3) return?

Chapter 2

Linked Lists and the Weighted Union

Keep every set as a list, pay for each head pointer you rewrite, and append the short list to the long one

First idea: keep each set as a linked list whose first node is the representative. Every node keeps a head pointer to the first node, so Find costs one step.

Union appends one list to the other, and every appended node needs a new head pointer: one rewrite each. Now always append the list of x, and run Union(0, 1), Union(0, 2), up to Union(0, n − 1). The list that holds 0 grows by one each time. Call the total head rewrites Unaive and the number of people n.

Say it aloud

U-naive equals one plus two, and so on up to n minus one, which equals n times n minus one, over two.

Unaive
U-naive the total head-pointer rewrites over the whole run, when we always append the list of x.
1 + 2 + … + (n − 1)
one plus two, up to n minus one the i-th union appends a list of i nodes and rewrites i head pointers.
n(n − 1)/2
n times n minus one, over two the closed form of that sum. It grows like n squared.
In plain words

Union number i rewrites i pointers. Add 1, 2, up to n − 1. Pair the first and last terms to get n(n − 1)/2 rewrites for n − 1 unions.

With numbers

n = 8: 1 + 2 + 3 + 4 + 5 + 6 + 7 = 8 × 7 / 2 = 28 rewrites. n = 1,000: 1,000 × 999 / 2 = 499,500 rewrites.

The fix is the weighted-union heuristic: store each list's length, and append the shorter list to the longer one. Follow one person, x. A rewrite of x means x was in the shorter list, so x's list at least doubles. Call the number of rewrites x suffers k.

Say it aloud

Two to the k is at most n, so k is at most log base two of n.

2k
two to the k the smallest size x's list can have after k rewrites: it at least doubles each time.
≤
is at most
n
n the number of people. No list can be longer.
k
k how many times one person's head pointer is rewritten, over the whole run.
log₂ n
log base two of n how many times you can double 1 before you pass n.
In plain words

Start with a list of 1 and double it k times: at least 2k people. That cannot pass n, so k is at most log₂ n. All n people together suffer at most n log₂ n rewrites.

With numbers

n = 64: log₂ 64 = 6, so no person is rewritten more than 6 times, and all 64 together at most 384 times. The naive run on 64 people pays 64 × 63 / 2 = 2,016.

Count the rewrites

Pick a sequence and drag n. Pink is the naive rule, green the weighted rule, the dashed line the n log₂ n ceiling.

64

"One list grows" runs Union(0, i) for i = 1 to n − 1. "Equal pairs" merges pairs, then quads, then eights: both rules pay the same there, (n/2) log₂ n.

This is CLRS Theorem 21.1: m operations on n elements take O(m + n log n) time. Charging each rewrite to the person who suffers it is the aggregate method of amortized analysis.

The failure. Symptom: merges slow down as groups grow. Measure: log each appended length; if it keeps growing, you append the big list. Fix: append the shorter list.

With the weighted union on 1,024 people, at most how many times can one person's head pointer be rewritten?

Chapter 3

The Forest of Parent Pointers

Store each set as a tree in one array, make Union one write, and watch Find pay the depth

Lists make Find cheap and Union expensive. Flip it. Keep each set as a rooted tree. Each node points to its parent, one level up. The root points to itself, and the root is the representative. All the trees together form a disjoint-set forest.

  1. MakeSet(x): set parent[x] = x.
  2. Find(x): follow parent pointers until a node points to itself. Return it.
  3. Union(x, y): find both roots. Make the second root a child of the first. One write.

The whole structure is one array of n integers. People are numbers 0 to n − 1, and parent[i] is the parent of i.

Watch the array and the trees

Press Next. A purple cell is the parent entry that just changed. A blue path is the walk a Find makes to the warm root.

Groups: Union(0, 1), Union(2, 3), Union(4, 5), Union(1, 3), Find(3), Union(3, 5), Find(5). A chain: Union(1, 0), Union(2, 1), up to Union(7, 6), then Find(0).

Trace the Groups script. After Union(0, 1), Union(2, 3) and Union(4, 5), the array is [0, 0, 2, 2, 4, 4]. Union(1, 3) finds roots 0 and 2 and sets parent[2] = 0: [0, 0, 0, 2, 4, 4]. Find(3) walks 3 → 2 → 0, two hops.

Now the danger. In the chain script, each Union puts the old root under a new person. After 7 unions, person 0 sits at depth 7, and Find(0) follows 7 pointers. With n people a chain has depth n − 1, so one Find costs n − 1 hops.

StructureFindUnion after the Finds
Linked lists, weighted1 stepup to n/2 rewrites
Plain forestdepth of x, up to n − 11 write

The forest looks worse. But the shape of a tree can change, and the next two chapters reshape it.

The failure. Symptom: a recursive Find raises RecursionError. Measure: print the depth of the deepest node; Python stops at 1,000 nested calls by default. Fix: write Find as a loop, then keep trees shallow with Chapters 4 and 5.

In a plain forest, Union is one write. Why can Find cost n − 1 hops?

Chapter 4

Union by Rank

Hang the shorter tree under the taller one, and prove the height never passes log₂ n

Hang a tree of height 10 under a tree of height 3, and the result has height 11. Hang the short tree under the tall one, and the height stays 10.

Union by rank makes that choice every time. Each node keeps a rank: an upper bound on the height of its tree, 0 for a new node. Union compares the ranks of the two roots.

  1. If one rank is lower, that root goes under the other. No rank changes.
  2. If the ranks are equal, the second root goes under the first, and the first root's rank goes up by 1.

Merge 16 people two ways

Pick a rule and an order, then drag the unions. Small numbers beside the roots are ranks.

15

Chain order is Union(1, 0), Union(2, 1), up to Union(15, 14). Pairs, then quads, is the tournament that builds the tallest tree rank allows. Random uses a fixed seed.

Why can the height not run away? A rank grows only when two roots of equal rank r merge. Call the number of nodes in the tree under x size(x).

Say it aloud

Size of x is at least two to the x-dot-rank.

size(x)
size of x the number of nodes in the tree under root x, x included.
≥
is at least
2x.rank
two to the x-dot-rank 2 multiplied by itself rank times. Rank 0 gives 1.
In plain words

A new node has rank 0 and size 1 = 20. Rank r + 1 appears only when two roots of rank r merge, and each brings at least 2r nodes. So size(x) is at least 2r + 2r = 2r+1. The rule holds at every step.

With numbers

Pairs, then quads, on 16 people: root 0 reaches rank 4 and holds 16 = 24 nodes. A rank-5 root would need at least 25 = 32 nodes, so with 16 people no rank passes 4.

The same count limits how many nodes reach a high rank. Call the number of nodes of rank r Nr.

Say it aloud

N-r is at most n over two to the r.

Nr
N-r how many nodes have rank exactly r.
n
n the number of elements.
/ 2r
over two to the r each rank-r node owned at least 2r nodes when it got that rank. No two of them share those nodes.
In plain words

Give each rank-r node its 2r or more nodes. No node goes to two of them, and there are only n. So at most n/2r nodes can have rank r. Set Nr = 1: the highest rank is ⌊log₂ n⌋, and so is the tallest tree.

With numbers

The 16-person tournament ends with 8 nodes of rank 0, 4 of rank 1, 2 of rank 2, 1 of rank 3 and 1 of rank 4. The ceilings are 16, 8, 4, 2 and 1. For n = 1,000,000, ⌊log₂ n⌋ = 19, so a Find follows at most 19 pointers.

Union by size hangs the smaller tree under the larger. It gives the same height bound, plus each group's size.

The failure. Symptom: depths pass log₂ n even with ranks. Measure: check that every root's tree has at least 2rank nodes. Fix: raise a rank only on a tie, for the root that stays on top.

With union by rank, a root has rank 5. At least how many nodes are in its tree?

Chapter 5

Path Compression

Make every node a Find passes point straight at the root, so the next Find is one hop

You ask for directions. Each person on the way says "ask my parent", until you reach the root. On the way back, you tell each of them: "the root is right there, skip the middle." The next person who asks gets there in one step.

That is path compression. Find(x) walks up to the root as before. Then it walks the same path again and sets each node's parent to the root. It changes no rank and no answer, only the shape.

Flatten a chain

The tree starts as a chain of 8 with root 0 at the top. Pick a node and press Find. Purple nodes had their parent rewritten. Then try the two cheaper variants.

The chain is parent = [0, 0, 1, 2, 3, 4, 5, 6]: node i hangs under node i − 1. A plain forest builds it from unlucky unions; union by rank never would. "Visited" counts the nodes the loop steps through below the root.

Trace Find(7) with full compression. The walk up visits 7, 6, 5, 4, 3, 2, 1 and reaches 0: 7 hops. The walk back sets parent to 0 for each of them. The array becomes [0, 0, 0, 0, 0, 0, 0, 0], and Find(7) again costs 1 hop.

Two variants do it in one pass. Path splitting points every node on the path at its grandparent. Path halving does the same for every other node, and jumps two levels each step. Their code differs in one line:

pythondef find(x):                    # full compression, two passes
    root = x
    while parent[root] != root:
        root = parent[root]
    while parent[x] != root:
        parent[x], x = root, parent[x]
    return root

def find_split(x):              # every node to its grandparent
    while parent[x] != x:
        nxt = parent[x]
        parent[x] = parent[nxt]
        x = nxt                     # step to the OLD parent
    return x

def find_halve(x):              # every other node to its grandparent
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]               # step to the NEW parent: skip one
    return x

On the chain, Find(7) with splitting visits 7 nodes and leaves 7 at depth 4. Halving visits 4 nodes and also leaves 7 at depth 4. Full compression leaves it at depth 1. With union by rank, all three give the same bound (Tarjan and van Leeuwen, 1984).

The failure. Symptom: Find returns the right root but stays slow. Measure: call Find(x) twice and count hops; the second call should cost 1. Fix: the second pass must write parent[x] = root for every node on the path.

Find(x) with full compression runs on a node at depth 5. What is x's depth afterwards?

Chapter 6

Both Tricks Together

Grow the workload from 16 to 16,384 people and watch only one curve stay flat

Each rule alone helps. Union by rank caps the height at log₂ n. Path compression alone also costs about log n per operation over a long run. Together they do far better. Measure it before we explain it.

Scale the workload

Pick a workload and drag n. Both axes are logarithmic. Each line is one strategy; the dots are your n.

1,024

Illustrative, seeded runs. "Groups then joiners" is the hero's workload at size n: about 2n operations. "Random" is 4n operations, half unions and half Finds on random people.

At n = 1,024 on the hero's workload, the plain forest pays 106 hops per operation. By rank pays 1.96, compression alone 2.85, and both together 0.97. At 16,384 people the plain forest pays 1,658, rank 2.67, compression 3.93. Both together still pay 0.96.

Why do they help each other? Rank keeps every path short, so each compression has little to rewrite. Compression then moves deep nodes up, so the same short path is not climbed twice. CLRS proves the result with a potential function over the ranks. Call the total number of operations m and the number of elements n.

Say it aloud

T of m and n is big O of m times alpha of n.

T(m, n)
T of m and n the worst-case total time of any sequence of m operations, n of them MakeSet.
O( )
big O of at most a fixed constant times what is inside, for large inputs.
m
m the number of MakeSet, Find and Union operations.
α(n)
alpha of n the inverse Ackermann function of Chapter 7. It is at most 4 for any n you can store.
In plain words

Charge each of the m operations at most a constant times α(n) steps. Add the charges: that bounds the whole run, T(m, n). Single operations can cost more; the total cannot.

With numbers

m = 10,000,000 operations on n = 1,000,000 people: α(n) = 4, so the run costs at most a constant times 40,000,000 steps. Union by rank alone allows up to 19 hops per Find, a bound of 190,000,000.

This is CLRS Theorem 21.14. Tarjan proved the bound in 1975. Later work showed that no structure of this kind can beat it in general, so α(n) is the true cost, not a weak analysis.

The failure. Symptom: a union-find with both rules still runs slow. Measure: count total hops over the run and divide by m; above 3 or so, a rule is missing. Fix: check that Union calls the compressing Find, and that ties raise a rank.

Why does the bound say "amortized O(α(n)) per operation" and not "every Find costs at most α(n)"?

Chapter 7

The Inverse Ackermann Function

Build a function that outgrows towers of powers, and turn it around to get one that barely moves

What is α(n), and why is it at most 4? It is the inverse of a function that grows faster than any tower of powers. Build that function in levels. Level 0 adds one. Each higher level repeats the level below many times.

Call the level k, the input j, and the function at level k Ak. This is CLRS's version.

Say it aloud

A-k of j equals j plus one when k is zero. When k is at least one, it equals A-k-minus-one applied j plus one times, starting from j.

Ak(j)
A-k of j the function at level k, applied to the whole number j.
j + 1
j plus one level 0: add one.
Ak−1(j+1)(j)
A-k-minus-one, applied j plus one times, to j start at j and apply the level below j + 1 times in a row. The superscript counts repeats, not a power.
In plain words

To get Ak(j), start with j. Apply level k − 1 to it, then to the result, j + 1 times in all. Level 1 works out to 2j + 1. Level 2 works out to 2j+1(j + 1) − 1.

With numbers

A1(1) = A0(A0(1)) = 3. A2(1) = A1(A1(1)) = A1(3) = 7. A3(1) = A2(A2(1)) = A2(7) = 28 × 8 − 1 = 2,047. A4(1) = A3(2,047), which is larger than A2(2,047), itself about 620 digits long.

Now turn it around. Call the number of elements n. The inverse asks how high a level you must climb before Ak(1) reaches n.

Say it aloud

Alpha of n equals the smallest k such that A-k of one is at least n.

α(n)
alpha of n the inverse Ackermann function: the level that first reaches n.
min { }
the smallest of the levels that pass the test.
k
k a level: 0, 1, 2, and so on.
Ak(1)
A-k of one level k applied to 1: 2, 3, 7, 2,047, then a number far past 1080.
n
n the number of elements.
In plain words

List A0(1), A1(1), A2(1) and so on: 2, 3, 7, 2,047, and then a giant. Walk down the list until a value is at least n. Its level is α(n).

With numbers

n = 1,000: 7 is too small, 2,047 is enough, so α(1,000) = 3. n = 1080 is about the number of atoms in the visible universe. 2,047 is too small and A4(1) is enough, so α(n) = 4.

Find alpha for any n

Drag n from 1 to 10100. The bands show the value of α(n). We squeeze the scale so the small bands stay visible.

1,000

Band edges from the CLRS definition: α(n) is 0 up to n = 2, 1 at n = 3, 2 from 4 to 7, and 3 from 8 to 2,047. It is 4 from 2,048 up to A4(1).

The failure. Symptom: a write-up says union-find is "O(log* n)" or "O(1)" and the numbers disagree with a friend's. Measure: check which definition each source uses; books shift the levels by one or two. Fix: say "O(m α(n)), and α(n) is at most 4 in practice", which every version agrees on.

Using Ak(1) = 2, 3, 7, 2,047, what is α(5,000)?

Chapter 8

Kruskal and Cycle Checks

Use two Finds to decide if an edge closes a cycle, and build a minimum spanning tree with them

Five towns need a road network. Each possible road has a cost. You want every town reachable for the least total cost. That network is a minimum spanning tree: it touches every town, has no loop, and has the smallest total weight.

Kruskal's algorithm builds it greedily:

  1. Sort the roads by cost, cheapest first.
  2. For each road (u, v): if Find(u) differs from Find(v), keep the road and call Union(u, v).
  3. If Find(u) equals Find(v), skip it. The towns already connect, so the road would close a loop.

Process the roads

Press Next. Teal is the road under test. Green roads stay, red dashed roads close a cycle. The row below is the parent array.

Roads (u, v, cost): (0, 1, 1), (2, 3, 2), (1, 3, 3), (0, 2, 4), (1, 2, 5), (3, 4, 6), (2, 4, 7). Union-find uses both rules.

Trace it. (0, 1, 1) and (2, 3, 2) join separate towns: keep both. (1, 3, 3) finds roots 0 and 2: keep, and the two pairs merge. (0, 2, 4) and (1, 2, 5) find root 0 on both ends: skip. (3, 4, 6) brings in town 4: keep. Four roads for five towns, total cost 1 + 2 + 3 + 6 = 12. The last road, (2, 4, 7), closes a cycle.

The cost: sorting E roads takes O(E log E). The 2E Finds and at most V − 1 Unions take O(E α(V)) in all. The sort dominates. A search for each road to detect a cycle would cost O(V + E) per road instead.

The same check finds the one extra edge in a graph that should be a tree: the first edge whose two ends already share a root. CLRS 23 proves that the greedy choice gives the minimum.

The failure. Symptom: the "tree" has more than V − 1 edges and its cost is too high. Measure: count the kept edges. Fix: test Find(u) against Find(v) before each Union, and skip on a match.

Kruskal's algorithm tests road (u, v), and Find(u) equals Find(v). What does that tell you?

Chapter 9

Percolation

Open cells one by one and use two extra nodes to see the moment water gets through

Pour water on a block of porous rock. Does it reach the bottom? Model the rock as a grid of cells, all blocked at first. Open cells at random, one at a time. The grid percolates when open cells link the top row to the bottom row through side-by-side neighbours.

Union-find tracks this live. Each cell is an element. When a cell opens, union it with each open neighbour.

Do not test every top cell against every bottom cell. Add two virtual nodes: one joined to every open top-row cell, one to every open bottom-row cell. The grid percolates when Find(top) equals Find(bottom). That is one comparison.

Open cells until water gets through

Open cells, or run until the grid percolates. Blue cells connect to the top. When the top meets the bottom, that cluster turns green. Then run 50 trials.

Random openings, fresh on each run. A cell joins its four side neighbours, not diagonals.

Run it a few times. On a 20 × 20 grid our 400 seeded runs percolated at 59.1% open on average, and most runs fell between 54% and 64%. On 40 × 40 the spread narrows to about 3 points around 59.2%. For huge grids the value settles near 59.27%. Below it, a grid almost never percolates; above it, it almost always does.

Each trial opens about 0.59 N cells for an N-cell grid and does a few Unions per cell. With both rules, a trial costs O(N α(N)): about linear. A search from the top after every opening would cost O(N) each time, O(N2) per trial.

The failure. Symptom: the grid reports "percolates" when no path exists, often because code joined a virtual node to the wrong row. Measure: look for a top or bottom node joined to a cell outside its row. Fix: union a cell with the top node only if it sits in row 0, and with the bottom node only if it sits in the last row.

Why add a virtual top node and a virtual bottom node?

Chapter 10

The Field Guide

Keep the terms, the numbers, the checks and the core code on one page

A disjoint-set structure answers one question: are x and y in the same set? Store each set as a tree in one parent array. Hang the lower-rank root under the higher, and point every node a Find passes at the root. Then m operations on n elements cost O(m α(n)), and α(n) is at most 4 for any n you can store.

Terms and numbers

TermMeaningNumber on this page
Representativethe member that names a set; the root of its treesame set exactly when Find(x) == Find(y)
Naive list unionalways append the list of xn(n − 1)/2 = 2,016 rewrites for n = 64
Weighted unionappend the shorter listat most log₂ n = 6 rewrites per person for n = 64
Plain forestsecond root under the first, no rulea chain of 8 has depth 7
Union by ranklower rank under higher; a tie raises one ranksize ≥ 2rank; height ≤ 19 for a million
Path compressionevery node on the Find path points at the rootFind(7) on the chain: 7 hops, then 1
Both rulesO(m α(n)) total, CLRS Theorem 21.140.97 hops per operation at n = 1,024
α(n)smallest k with Ak(1) ≥ nAk(1) = 2, 3, 7, 2,047; α(1080) = 4
Kruskalsorted edges; keep an edge when the roots differ4 roads, cost 12
Percolationtop meets bottom through open cellsabout 59.3% open on large grids

Before you ship a union-find

  1. Compare roots, Find(x) == Find(y), never parents.
  2. Link roots in Union, never the two elements.
  3. Use union by rank or by size, and raise a rank only on a tie.
  4. Compress in Find. Write it as a loop if trees can be deep.
  5. Return True or False from Union, so callers can spot a cycle.
  6. Do not expect deletions or paths: union-find only merges and answers yes or no.

The core code

pythonclass UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))   # MakeSet for 0 .. n-1
        self.rank = [0] * n
        self.count = n                    # number of sets

    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:      # path compression
            self.parent[x], x = root, self.parent[x]
        return root

    def union(self, x, y):
        rx, ry = self.find(x), self.find(y)
        if rx == ry:
            return False                  # already together: a cycle
        if self.rank[rx] < self.rank[ry]:
            rx, ry = ry, rx               # union by rank
        self.parent[ry] = rx
        if self.rank[rx] == self.rank[ry]:
            self.rank[rx] += 1
        self.count -= 1
        return True

uf = UnionFind(6)
for a, b in [(0, 1), (2, 3), (0, 3)]:
    uf.union(a, b)
print(uf.find(1) == uf.find(2), uf.count)   # True 3

Where it shows up, and where it does not

JobUnion-find?
Groups that only merge, "same group?" questionsYes
Cycle check in an undirected graph, KruskalYes
Merging records that share a key (accounts with one email)Yes
Shortest paths, or the path itselfNo: use a search or Dijkstra
Directed reachabilityNo: use a search or strongly connected components
Edges that can be deletedNo: it cannot split a set

Keep going

The takeaway. Two local rules, hang the short tree under the tall one and point the path at the root, turn a structure that can cost n per question into one that costs about one.
Which job is a poor fit for union-find?

Now press Present or Teach. Explain from memory why a rank-r root holds at least 2r nodes, what one compressed Find does to the path, and why α(n) stays at 4. Then go back to the hero, switch from Plain to Both, and say how many pointer hops you saved.

Source

T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 21, Data Structures for Disjoint Sets (third edition numbering). The definitions of Ak and α follow the book; the devices, the toy workloads and the simulated costs on this page are our own.

CLRS Chapter 21 · Data Structures for Disjoint Sets
Next: Elementary Graph Algorithms · Back to Gleams