Union-find
Union-find (disjoint-set) keeps a partition of elements into groups. find returns a group's representative. union merges two groups. With path compression and union by rank, both operations are nearly O(1).
Detailed Explanation
You have n items. You need to ask "are these two already connected?" and "connect them" many times. A DFS per query is too slow. Union-find stores a parent pointer per item. A root's parent is itself. find(x) walks to the root. Path compression sets every walked node to the root so the next walk is short. Union by rank (or by size) attaches the smaller tree under the larger so the height stays small.
The amortized time per operation is inverse-Ackermann, which is less than 5 for any size you will see. That is why Kruskal's MST sorts edges and unions endpoints if they are not already in one component. It is also why "number of provinces", "accounts merge", and grid "connect cells" problems run fast.
In Java you store int[] parent and int[] rank (or size). find is recursive or a short loop; the loop form cannot overflow the stack. Return the root and assign parent[x] = root on the way out. union returns whether it merged, which is useful for counting components: start at n, subtract one per successful merge.
You reach for union-find when connections are incremental and you do not need the actual path. You reach for DFS/BFS when you need distances or the nodes in a component as a list and the graph is static. You reach for a full graph structure when edges have weights you must relax.
The cost of skipping union by rank is a line-shaped tree and O(n) finds until compression fixes it. The cost of using Integer parents is boxing. The cost of 1-based ids is an off-by-one; pick 0-based and stick to it. Union-find does not support splitting a group again. If you need rollbacks, you need a different structure (persistent or undo stack of parent changes).
Code Examples
public class Dsu {
private final int[] parent;
private final int[] rank;
private int parts;
Dsu(int n) {
parent = new int[n];
rank = new int[n];
parts = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // path compression
}
return parent[x];
}
boolean union(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) {
return false;
}
if (rank[ra] < rank[rb]) {
parent[ra] = rb;
} else if (rank[ra] > rank[rb]) {
parent[rb] = ra;
} else {
parent[rb] = ra;
rank[ra]++;
}
parts--;
return true;
}
public static void main(String[] args) {
Dsu d = new Dsu(4);
d.union(0, 1);
d.union(2, 3);
System.out.println(d.find(0) == d.find(1)); // prints: true
System.out.println(d.find(0) == d.find(2)); // prints: false
System.out.println(d.parts); // prints: 2
}
}Common Gotchas
`find` without compression plus no rank can degrade to O(n)
implement both.
Union on already-connected nodes should be a no-op
do not decrement the component count.
Recursive `find` on a degenerate chain can overflow before compression helps
a loop is safer on huge n.
Union-find cannot split
plan for that if the problem deletes edges.