Graph Theory, Step by Step

Free course
Chapter 3 quiz first

First, check Chapter 3

Take the Chapter 3 quiz: 10 questions, and you pass with 7 correct. You can retake it as often as you like.

Who Is in My Group?

Chapter 4, lesson 1 of 2

Union-find: are two things connected? Answered almost instantly.

Written lesson

7 min read

Friendships arrive one at a time. Ana befriends Ben, Cara befriends Dan, and so on, millions of them a day. At any moment someone asks: are Ana and Omar linked, through friends of friends? You could search the whole network for every question, but with millions of questions, even a fast search is far too slow.

A tiny data structure called union-find answers it almost instantly, however big the network grows, and it takes two small ideas to make it fast. This lesson covers how union-find stores groups, why the simple version is slow, the two tricks that fix it, and where it is used.

The question

The question is always the same: are two people in the same group? And the groups only ever grow, one friendship at a time.

Two simple ideas are each slow somewhere:

  • Search for each question. A search explores the whole group, so every question costs up to the size of the network. With a million people and ten million questions, that could mean ten trillion steps.
  • A group label for everyone. A question is instant: compare two labels. But a merge must relabel everyone in one of the groups. On our stream of eight friendships, merges relabel 12 people in total, and the last friendship alone relabels four.

A label each: questions are instant, merges are slow.A label each: questions are instant, merges are slow.

Union-find sits in between: both questions and merges become almost free.

A forest

Union-find stores each group as a tree. Every person points to a parent, and following the parents always leads to one person at the top: the root. The root is the name of the group. A person who is alone is their own root.

  • find(x) walks up from x to its root. Two people are in the same group exactly when their roots are the same.
  • union(a, b) joins two groups by making one root point to the other. Nothing else moves, so a union is just one pointer change.

Every group is a tree, and the root names it.Every group is a tree, and the root names it.

The idea is older than any social network. Storing groups as trees was published in 1964 by Bernard Galler and Michael Fischer, for compilers that had to track which variables share the same memory.

Run it by hand

Start with eight people, each alone, each their own root. The friendships arrive in this order (with union by rank, explained in the next section: on a tie, the first person's root stays on top):

#FriendshipWhat happens
1Ana, BenBen now points to Ana.
2Cara, DanDan points to Cara.
3Eva, FinnFinn points to Eva.
4Ben, Carafind(Ben) = Ana, find(Cara) = Cara. Cara now points to Ana: four people in one tree.
5Gus, OmarOmar points to Gus.
6Ana, Danfind(Dan) walks Dan, Cara, Ana: the same root as Ana. Already linked, so union changes nothing and reports it.
7Finn, GusGus hangs under Eva.
8Dan, EvaThe two trees join under Ana.

Friendship 6 is rejected: Ana and Dan are already in one group.Friendship 6 is rejected: Ana and Dan are already in one group.

Are Ana and Omar linked? After friendship 7, find(Omar) walks Omar, Gus, Eva, while Ana is her own root. Different roots: no. After friendship 8, Omar leads to Eva and then to Ana: yes.

After friendship 8: one tree, rooted at Ana.After friendship 8: one tree, rooted at Ana.

Eight friendships, one tree, and nobody is ever more than two steps from the root.

Keep it shallow

The danger is in how trees are joined. Join them carelessly, always hanging the first root under the second, and seven unions in a row build a chain of eight. A find from the bottom then walks seven steps, and on a million people, a million.

Careless unions build a chain.Careless unions build a chain.

Fix 1: union by rank. Each root remembers a rank, an upper limit on its height.

  • Always hang the root of lower rank under the root of higher rank. The rank does not change.
  • Only when two roots of equal rank meet does the new root's rank grow by one.

Why that keeps trees shallow. To reach rank 1 you need two people. To reach rank 2, two trees of rank 1, so at least four people. Each new rank needs two trees of the rank below, so it at least doubles the size:

A tree of rank r holds at least 2^r people. So with n people, no rank, and no height, is ever more than log₂ n.

Each rank at least doubles the size.Each rank at least doubles the size.

Our eight people end in one tree of rank 3, exactly log₂ 8. The real height is only 2: rank is an upper limit, not the height itself, because path compression (next) can flatten a tree without lowering its rank. That is fine, since rank only decides which root goes on top. Hanging the smaller group under the larger (union by size) works just as well.

Flatten it

Fix 2: path compression. Every time find walks up to a root, it points every person it passed straight at that root.

In our guide's picture, a find from 4 walks 4, 3, 2, 1. Afterwards 2, 3 and 4 all point directly to 1, and the next find from any of them is a single step.

Path compression: after one find, everyone on the path points at the root.Path compression: after one find, everyone on the path points at the root.

We saw it in our stream too: during friendship 6, the find from Dan passed Cara, and afterwards Dan pointed straight at Ana.

A popular variant points each person at its grandparent instead, called path halving. It needs no recursion, and it is just as fast.

With both tricks together, any sequence of m operations on n people costs O(m · α(n)), where α is the inverse Ackermann function. Robert Tarjan proved this bound in 1975, and α grows so slowly that it never exceeds 4 for any input you could ever store. In practice: almost exactly one step per operation.

In the world

In Python, the whole structure is a short class with two lists, parent and rank. Find calls itself to compress the path, and union returns False when the two were already linked:

class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

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

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False  # already in one group
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra  # union by rank
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        return True

names = ["Ana", "Ben", "Cara", "Dan", "Eva", "Finn", "Gus", "Omar"]
ix = {name: i for i, name in enumerate(names)}
stream = [("Ana", "Ben"), ("Cara", "Dan"), ("Eva", "Finn"), ("Ben", "Cara"),
          ("Gus", "Omar"), ("Ana", "Dan"), ("Finn", "Gus"), ("Dan", "Eva")]
uf = UnionFind(8)
[uf.union(ix[a], ix[b]) for a, b in stream]  # [True, True, True, True, True, False, True, True]

That False is the key to the next lesson. When Kruskal builds the cheapest network, union-find tells it which roads would only close a loop. The same test:

  • finds cycles in any undirected graph: an edge whose ends already share a root closes a cycle;
  • counts connected components: every successful union turns two groups into one, so eight people and seven successful unions leave 8 − 7 = 1 group;
  • groups the pixels of an image into regions;
  • answers the classic interview question find the redundant connection: here, friendship 6.

Physicists use it for percolation: can water seep through a grid of open cells? Union each open cell with its open neighbours, and water gets through when the top row and the bottom row share a root.

Percolation: open cells joined with union-find.Percolation: open cells joined with union-find.

One limit: union-find can only merge. If Ana and Ben stop being friends, it cannot split them apart again.

Key ideas

  • Union-find keeps each group as a tree of parent pointers, and the root names the group.
  • Find walks up to the root. Union makes one root point to another, and reports when the two were already linked.
  • Union by rank keeps the trees shallow (height at most log₂ n), and path compression flattens them as you go.
  • Together, every operation costs almost exactly one step.

Check yourself

1. Ten people start alone and six unions succeed. How many groups are there now?

2. With union by rank, how tall can a tree of 1,000 people be at most?

3. You process the edges A-B, B-C, C-D, D-B with union-find. Which one closes a cycle?

Practice on the platform

The union-find guide shows the class and both tricks in detail. In the Kruskal visualizer, union-find runs inside Kruskal: import the eight friendships, weighted by their order, and run it. Friendship 6 is rejected, because Ana and Dan were already in one group; every other friendship joins two groups.

Up next

Course content

0 of 20 watched

Chapter 1Graph Theory Foundations

Chapter 2Exploring a GraphChapter 1 quiz first

Chapter 3Shortest PathsChapter 2 quiz first

Chapter 4Connecting CheaplyChapter 3 quiz first

Chapter 5Hard ProblemsChapter 4 quiz first

Chapter 6Network FlowsChapter 5 quiz first