Skip to lesson

Disjoint set union

Union-Find manages non-overlapping partitions of elements, supporting near-instant connectivity queries and set merges.

The disjoint set data structure

Disjoint set union (union-find) keeps track of groups of elements and can merge two groups or check whether two elements are in the same group in almost O(1) time.

Union-Find manages a partition of elements into non-overlapping sets. It supports two operations: find and union. Find identifies which set contains an element, while union merges two sets.

A naive implementation uses an integer array parent where parent[i] = i initially. To merge sets containing u and v, find their roots and link parent[rootU] = rootV. However, naive linking can degrade trees into linear chains of depth O(N).

Union-Find step-by-step trace

Step 1 of 5

0123
p0
0
p1
1
p2
2
p3
3
Initially every element is its own root parent: parent = [0, 1, 2, 3].

In the worst case without optimisations, find takes linear O(N) time. Performing M operations then takes quadratic O(M * N) time. Two critical optimisations reduce this runtime to near-constant speed.

Path compression and union by rank

Path compression flattens the tree during find queries. When finding the representative of element u, reassign parent[u] directly to the root. Future queries for u or its descendants resolve in immediate O(1) steps.

Example 1 · Union-Find with Path Compression and Rank in Java

Main.javaJava
public class Main {    static class DSU {        int[] parent;        int[] rank;        int count;
        DSU(int n) {            parent = new int[n];            rank = new int[n];            count = n;            for (int i = 0; i < n; i++) parent[i] = i;        }
        int find(int i) {            if (parent[i] == i) return i;            return parent[i] = find(parent[i]); // Path compression        }
        boolean union(int i, int j) {            int rootI = find(i);            int rootJ = find(j);            if (rootI == rootJ) return false;
            // Union by rank            if (rank[rootI] < rank[rootJ]) {                parent[rootI] = rootJ;            } else if (rank[rootI] > rank[rootJ]) {                parent[rootJ] = rootI;            } else {                parent[rootJ] = rootI;                rank[rootI]++;            }            count--;            return true;        }
        boolean connected(int i, int j) {            return find(i) == find(j);        }    }
    public static void main(String[] args) {        DSU dsu = new DSU(5);        dsu.union(0, 1);        dsu.union(2, 3);        dsu.union(1, 2);
        System.out.println("0 and 3 connected: " + dsu.connected(0, 3));        System.out.println("0 and 4 connected: " + dsu.connected(0, 4));        System.out.println("Components count: " + dsu.count);    }}
Output
0 and 3 connected: true
0 and 4 connected: false
Components count: 2

What this code does

  • find flattens trees by setting parent[i] to the root recursively.
  • union merges sets by rank and decrements overall component count.
  • connected queries run in near-constant amortized O(alpha(N)) time.

Union by rank maintains a rank array tracking the approximate tree height. When merging sets, always attach the shorter tree under the taller tree. If both trees share equal rank, attach one and increment the winner's rank by 1. Combined, path compression and union by rank yield O(alpha(N)) amortized time. The inverse Ackermann function alpha(N) remains below 5 for all practical inputs. Consequently, both operations run in nearly constant O(1) effective time.

Fix the error

Fix the find method

Read the error, then pick the line that fixes it.

This find method with path compression will not compile. Choose the line that fixes it.

public class Main {
static int find(int[] parent, int i) {
if (parent[i] == i) return i;
parent[i] = find(parent, parent[i]);
}
public static void main(String[] args) {
int[] parent = {0, 0, 1};
System.out.println(find(parent, 2));
}
}

Error

Main.java:5: error: missing return statement

Cycle detection and network connectivity

Union-Find solves dynamic connectivity problems in undirected graphs. Consider checking whether two computer servers belong to the same subnetwork. A single call to find(u) == find(v) answers connectivity queries instantly.

Example 2 · Redundant Connection Cycle Detection in Java

Main.javaJava
import java.util.*;
public class Main {    static int find(int[] parent, int i) {        if (parent[i] == i) return i;        return parent[i] = find(parent, parent[i]);    }
    static int[] findRedundantConnection(int[][] edges) {        int n = edges.length;        int[] parent = new int[n + 1];        for (int i = 1; i <= n; i++) parent[i] = i;
        for (int[] e : edges) {            int rootU = find(parent, e[0]);            int rootV = find(parent, e[1]);            if (rootU == rootV) return e; // Cycle detected            parent[rootU] = rootV;        }        return new int[0];    }
    public static void main(String[] args) {        int[][] edges = {{1, 2}, {1, 3}, {2, 3}};        int[] redundant = findRedundantConnection(edges);        System.out.println("Redundant edge: " + Arrays.toString(redundant));    }}
Output
Redundant edge: [2, 3]

What this code does

  • Edge (2, 3) connects vertices already sharing root parent 3.
  • Detects the exact edge creating a cycle in the undirected graph.
  • Linear O(N alpha(N)) time replaces slower DFS cycle searches.

Example 3 · Brute force: relabel every vertex on each union, O(n) per union

Main.javaJava
public class Main {    static int countComponents(int n, int[][] edges) {        int[] label = new int[n];        for (int i = 0; i < n; i++) label[i] = i;        int count = n;
        for (int[] e : edges) {            int a = label[e[0]];            int b = label[e[1]];            if (a != b) {                for (int i = 0; i < n; i++) {      // touch every vertex to merge two groups                    if (label[i] == a) label[i] = b;                }                count--;            }        }        return count;    }
    public static void main(String[] args) {        int[][] edges = {{0, 1}, {1, 2}, {3, 4}};        System.out.println("Connected components: " + countComponents(5, edges));    }}
Output
Connected components: 2

What this code does

  • Every vertex stores its group label, so "same group?" is one comparison.
  • Merging two groups rewrites the label of every member, which costs O(n) for each edge.
  • With n vertices and n edges that is O(n^2) in total.

Example 4 · Better: parent links without compression, O(n) worst case per find

Main.javaJava
public class Main {    static int find(int[] parent, int i) {        while (parent[i] != i) i = parent[i];      // walk up to the root, no shortcuts        return i;    }
    static int countComponents(int n, int[][] edges) {        int[] parent = new int[n];        for (int i = 0; i < n; i++) parent[i] = i;        int count = n;
        for (int[] e : edges) {            int rootU = find(parent, e[0]);            int rootV = find(parent, e[1]);            if (rootU != rootV) {                parent[rootU] = rootV;             // one write merges two groups                count--;            }        }        return count;    }
    public static void main(String[] args) {        int[][] edges = {{0, 1}, {1, 2}, {3, 4}};        System.out.println("Connected components: " + countComponents(5, edges));    }}
Output
Connected components: 2

What this code does

  • A union is now one write, instead of a rewrite of the whole group.
  • The cost moved into find, which walks up the parent chain.
  • A long chain makes find O(n), so path compression is the next fix.

Example 5 · Optimal: path compression, almost O(1) per operation

Main.javaJava
public class Main {    static int find(int[] parent, int i) {        if (parent[i] == i) return i;        return parent[i] = find(parent, parent[i]);    }
    static int countComponents(int n, int[][] edges) {        int[] parent = new int[n];        for (int i = 0; i < n; i++) parent[i] = i;        int count = n;
        for (int[] e : edges) {            int rootU = find(parent, e[0]);            int rootV = find(parent, e[1]);            if (rootU != rootV) {                parent[rootU] = rootV;                count--;            }        }        return count;    }
    public static void main(String[] args) {        int[][] edges = {{0, 1}, {1, 2}, {3, 4}};        System.out.println("Connected components: " + countComponents(5, edges));    }}
Output
Connected components: 2

What this code does

  • Initial component count equals n isolated vertices.
  • Successful union operations decrement component count by 1.
  • Returns 2 components: {0, 1, 2} and {3, 4}.
  • Path compression flattens each chain it walks, so later finds jump straight to the root and the total cost is almost linear.

Union-Find also provides cycle detection in undirected graphs. Iterate through all undirected edges [u, v] one by one. If find(u) equals find(v), an existing connection already exists, proving a cycle. Otherwise, call union(u, v) to merge their respective components. This mechanism forms the core foundation of Kruskal's minimum spanning tree algorithm. It also tracks the total count of independent connected components dynamically.

Next step

Check your understanding

10 quick questions