Reading history

Union-Find (Disjoint Set Union) in C

5 min read 1 views

Learn union-find in C: find and union, path compression, union by rank, counting connected groups and detecting cycles in undirected graphs.

Imagine tracking which people in a social network belong to the same friend circle while new friendships keep arriving. You need two quick operations: merge two groups, and ask whether two people are already in the same group. The union-find structure, also called a disjoint set union (DSU), does both in almost constant time using nothing more than an integer array. It is a key building block for Kruskal’s algorithm, cycle detection and network connectivity.

In this lesson you will learn

  • Representing groups as trees stored in a parent array
  • The find and union operations
  • Path compression and union by rank
  • Counting connected groups
  • Detecting a cycle in an undirected graph

It helps to know recursion and the basics of graphs.

Find and Union

#include <stdio.h>

#define N 8

int parent[N], rank_[N];

void make_sets(void) {
    for (int i = 0; i < N; i++) { parent[i] = i; rank_[i] = 0; }
}

/* find with path compression: point every node on the path straight at the root */
int find(int x) {
    if (parent[x] != x) parent[x] = find(parent[x]);
    return parent[x];
}

/* union by rank: attach the shorter tree under the taller one */
int unite(int a, int b) {
    int ra = find(a), rb = find(b);
    if (ra == rb) return 0;                         /* already in the same set */
    if (rank_[ra] < rank_[rb]) { int t = ra; ra = rb; rb = t; }
    parent[rb] = ra;
    if (rank_[ra] == rank_[rb]) rank_[ra]++;
    return 1;
}

int main(void) {
    make_sets();
    int pairs[][2] = {{0, 1}, {2, 3}, {1, 3}, {4, 5}, {6, 7}, {5, 7}, {0, 3}};
    for (int i = 0; i < 7; i++) {
        int a = pairs[i][0], b = pairs[i][1];
        printf("union(%d, %d): %s\n", a, b, unite(a, b) ? "merged" : "already connected");
    }
    printf("connected(0, 2)? %s\n", find(0) == find(2) ? "yes" : "no");
    printf("connected(0, 4)? %s\n", find(0) == find(4) ? "yes" : "no");

    int groups = 0;
    for (int i = 0; i < N; i++) if (find(i) == i) groups++;
    printf("number of groups: %d\n", groups);
    return 0;
}

Output

union(0, 1): merged
union(2, 3): merged
union(1, 3): merged
union(4, 5): merged
union(6, 7): merged
union(5, 7): merged
union(0, 3): already connected
connected(0, 2)? yes
connected(0, 4)? no
number of groups: 2
  • Every element starts as its own group: parent[i] = i. An element whose parent is itself is the root, or representative, of its group.
  • find(x) follows parent links up to the root. Two elements are in the same group exactly when they have the same root.
  • Path compression: on the way back from the recursion, every visited node is pointed directly at the root, so later finds on those nodes take one step.
  • unite joins two groups by making one root the parent of the other. Union by rank attaches the shorter tree under the taller one, keeping the trees flat.
  • The union of 0 and 3 reports “already connected”, because 0–1, 2–3 and 1–3 have already joined them. At the end, {0,1,2,3} and {4,5,6,7} form 2 groups.

Detecting a Cycle

#include <stdio.h>

/* Detect a cycle in an undirected graph with union-find */
#define V 6
int parent[V];

int find(int x) { return parent[x] == x ? x : (parent[x] = find(parent[x])); }

int main(void) {
    int edges[][2] = {{0, 1}, {1, 2}, {3, 4}, {2, 5}, {4, 5}, {5, 0}};
    int E = 6;
    for (int i = 0; i < V; i++) parent[i] = i;

    for (int i = 0; i < E; i++) {
        int u = edges[i][0], v = edges[i][1];
        int ru = find(u), rv = find(v);
        if (ru == rv) {
            printf("edge %d-%d joins two vertices already connected: CYCLE found\n", u, v);
            return 0;
        }
        parent[ru] = rv;
        printf("edge %d-%d added\n", u, v);
    }
    printf("no cycle\n");
    return 0;
}

Output

edge 0-1 added
edge 1-2 added
edge 3-4 added
edge 2-5 added
edge 4-5 added
edge 5-0 joins two vertices already connected: CYCLE found
  • Edges are added one at a time. If both ends of a new edge already have the same root, a path already connects them, so this edge closes a loop.
  • Edge 5–0 is the one that completes the cycle 0–1–2–5–0.
  • This compact find uses the same path compression in one line with the conditional operator.
  • The same test is the heart of Kruskal’s minimum spanning tree algorithm.

Complexity

Versionfind / union (per operation)
No optimisationO(n) in the worst case (tree becomes a chain)
Union by rank onlyO(log n)
Path compression onlyO(log n) amortised
Both togetherO(α(n)) amortised, effectively constant

α(n) is the inverse Ackermann function, which is at most 4 for any input size that could ever fit in a computer.

Common Mistakes

  1. Linking elements instead of roots: always join find(a) and find(b), not a and b.
  2. Forgetting to initialise parent[i] = i.
  3. Comparing parents instead of roots to check connection.
  4. Using union-find for directed graphs; it only detects cycles in undirected graphs. Use DFS or topological sort for directed ones.

Practice Exercises

Exercise 1. Extend the structure to report the size of the group containing any element.

Show answer
int size_[N];                       /* set size_[i] = 1 in make_sets */
/* in unite, after parent[rb] = ra: */
size_[ra] += size_[rb];
/* query: */
int group_size(int x) { return size_[find(x)]; }

Exercise 2. There are 5 computers and cables 0–1, 1–2 and 3–4. How many extra cables are needed to connect everything?

Show answer

After the unions there are 2 groups ({0,1,2} and {3,4}). Connecting k groups needs k − 1 cables, so 1 more cable.

Frequently Asked Questions

Can union-find split a group again?

No. The basic structure only supports merging. Problems that need splitting are often solved by processing the operations in reverse, so that splits become merges.

Why is the array called rank and not height?

Path compression changes the real heights, and updating them would be costly. Rank is an upper bound on the height that is only changed during unions, which is enough to keep the trees flat.

Summary

  • Groups are trees in a parent array; the root represents the group.
  • find locates the root; union joins two roots.
  • Path compression plus union by rank make operations nearly O(1).
  • Used for connectivity, cycle detection and Kruskal’s algorithm.

Next: Topological Sort in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *