Union-find and spanning trees

Advanced

Introduction

Sometimes the questions come as a stream: "connect A and B", "are A and C in the same group?", "how many groups are left?". Running a DFS after every change is far too slow. Union-find, also called a disjoint set union (DSU), keeps the groups in a forest of small trees and answers each operation in almost constant time.

How it works

The forest

Each item has a parent. At the start, every item is its own parent, so every item is its own group. The root of a tree, the item that is its own parent, stands for the whole group.

  • find(x) follows parents up to the root.
  • unite(a, b) finds both roots; if they differ, it hangs one root under the other.

Two items are in the same group exactly when find(a) == find(b).

Two small ideas that make it fast

Path compression: while finding the root, point every item on the way straight at the root, with parent[x] = find(parent[x]). Later finds on the same items take one step.

Union by size: when merging, attach the smaller group under the larger one, so the trees stay shallow. Keep a sz array with the size of each root's group.

With both, an operation costs the inverse Ackermann function of n, which is under 5 for any input you will ever meet. We treat it as constant.

Kruskal's minimum spanning tree

To connect all vertices with the cheapest set of edges: sort the edges by cost; go through them in order; add an edge when unite says it joins two different groups, and skip it otherwise (it would make a cycle). After the loop, if n - 1 edges were added, their total cost is the minimum; if fewer, the graph is not connected.

Find is recursive. With path compression, a long chain can only appear early on, and compression flattens it. For very large n, an iterative find avoids deep recursion.

Example

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

vector<int> parent(6), sz(6, 1);

int find(int x) {
    if (parent[x] != x) parent[x] = find(parent[x]);
    return parent[x];
}

bool unite(int a, int b) {
    a = find(a);
    b = find(b);
    if (a == b) return false;
    if (sz[a] < sz[b]) swap(a, b);
    parent[b] = a;
    sz[a] += sz[b];
    return true;
}

int main() {
    for (int i = 0; i < 6; i++) parent[i] = i;
    int groups = 6;
    int links[4][2] = {{0, 1}, {2, 3}, {1, 3}, {0, 2}};
    for (int i = 0; i < 4; i++) {
        bool merged = unite(links[i][0], links[i][1]);
        if (merged) groups--;
        cout << "link " << links[i][0] << "-" << links[i][1] << (merged ? " merges" : " is already inside a group") << ", groups: " << groups << "\n";
    }
    cout << "size of the group of 0: " << sz[find(0)] << "\n";
    return 0;
}
Open in compiler

Six items start in separate groups. Four links are added; the program shows whether each one merges two groups or joins items that are already together.

Line by line

  • parent and sz are the two arrays; sz[r] is the group size of root r.
  • find compresses the path as it returns.
  • unite returns false if both items already have the same root; otherwise it attaches the smaller group to the larger one and adds the sizes.
  • groups-- happens only when two groups really merged.
  • The link 0-2 comes last: 0 and 2 are already together through 0-1, 1-3 and 2-3, so it changes nothing.

Expected result

link 0-1 merges, groups: 5
link 2-3 merges, groups: 4
link 1-3 merges, groups: 3
link 0-2 is already inside a group, groups: 3
size of the group of 0: 4

In the real world

Union-find tracks which computers are connected in a growing network, which pixels belong to the same region in image segmentation, and which accounts belong to the same person when records are merged. Kruskal's algorithm plans the cheapest cabling, road or pipe network that links all sites, and is used in clustering data too.

Common mistakes

  • Comparing parent[a] and parent[b] instead of find(a) and find(b).
  • Forgetting to set parent[i] = i at the start.
  • Adding sizes without first finding the roots.
  • Counting groups wrongly: decrease the count only when unite returns true.
  • Using Kruskal on a graph that is not connected and not checking the edge count.

Best practices

  • Write find and unite once and test them on a tiny input.
  • Always use both path compression and union by size.
  • Let unite return whether it merged, and use that result.
  • Use long long for the total cost in Kruskal.
  • After Kruskal, check that exactly n - 1 edges were taken.

Summary

Union-find keeps groups as trees of parents, with find to get the root and unite to merge two groups. Path compression and union by size make it nearly constant time per operation. Together with a sort of the edges, it gives Kruskal's minimum spanning tree.

Quick check

1. How do you test whether a and b are in the same group?
2. What does path compression do?
3. In Kruskal's algorithm, when is an edge skipped?
4. unite(a, b) returns false. What does that tell you?

Key takeaways

  • find(x) returns the root of x's group; two items are together when their roots are equal
  • Path compression plus union by size makes each operation nearly constant
  • Unite returns false when the two items were already together, which signals a cycle
  • Kruskal sorts the edges and adds each one that joins two different groups

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.