Advanced 12 min

Union-find and connected groups

Union-find keeps track of which items are in the same group as groups are joined.

How it works

Write parent arrows for a group with root A. A find operation follows arrows until it reaches a node pointing to itself. Compression redirects visited nodes closer to the root. A query about whether two items are connected compares their roots, while a union actually links the groups.

Walk through an example

Initially every item points to itself. To join A and B, find the representative of each group and connect the representatives. Path compression makes future lookups shorter.

What to watch for

Join group representatives instead of arbitrary nodes. Union by size or rank helps keep chains short before compression.

Code example

def find(parent, x):
    while x != parent[x]:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x

Check your understanding

Which items share a group with A?

See the example and explanation
Worked example
Given Join A with B, then B with C. D stays alone.
Answer A, B, and C

The first join puts A and B together. The second joins that whole group to C.

Open practice problem
Next lessonTopological sorting