Disjoint Set Union (DSU), also known as Union-Find, is one of the most elegant data structures in competitive programming. It efficiently handles dynamic connectivity queries and has applications ranging from graph problems to grid traversals. Here's a curated list of interesting DSU problems that will sharpen your skills!
DSU excels at:
class DSU {
private int[] parent;
private int[] rank;
private int components;
public DSU(int n) {
parent = new int[n];
rank = new int[n];
components = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // Path compression
}
return parent[x];
}
public boolean union(int x, int y) {
int px = find(x);
int py = find(y);
if (px == py) {
return false; // Already in same set
}
// Union by rank
if (rank[px] < rank[py]) {
int temp = px;
px = py;
py = temp;
}
parent[py] = px;
if (rank[px] == rank[py]) {
rank[px]++;
}
components--;
return true;
}
public boolean connected(int x, int y) {
return find(x) == find(y);
}
public int countComponents() {
return components;
}
}Time Complexity: Nearly O(1) per operation with path compression and union by rank (technically O(α(n)) where α is the inverse Ackermann function)
The perfect introduction to DSU! Given a graph of cities, find the number of connected components (provinces).
Key Insight: Each union operation merges two provinces. Count the number of distinct root nodes.
A fantastic problem that combines DSU with string processing!
Key Insight: Union accounts that share at least one email. Use a map to track email→account_id relationships.
Find the edge that creates a cycle in an undirected graph.
Key Insight: Process edges sequentially. The first edge where both nodes already belong to the same component creates a cycle!
This is where DSU truly shines! Given queries asking if a path exists with all edges < limit, answer offline.
Key Insight:
One of my favorite DSU problems! Three types of edges: Alice-only, Bob-only, and shared.
Key Insight:
Strings are similar if they differ by exactly 2 positions. Group similar strings.
Key Insight: Treat each string as a node. Union similar strings. This demonstrates DSU's power with non-traditional "nodes"!
You can swap characters at positions connected by given pairs. Find lexicographically smallest string.
Key Insight:
Two numbers are connected if they share a common factor > 1. Find the largest component.
Key Insight:
Given equations like "a==b" and "b!=c", determine if all can be satisfied.
Key Insight:
Find path from top-left to bottom-right minimizing maximum absolute difference.
Key Insight:
What are your favorite DSU problems? Share your insights and alternative approaches below! 🚀