Learn the pattern · ~15 min
Union-Find (Disjoint Set)
also called DSU, disjoint sets
Give every group one representative. Two items are connected exactly when they lead to the same representative, and merging two groups is one pointer change.
Reach for it when you read
- +"Are a and b in the same group?" asked many times while connections keep arriving.
- +Merging things that share something: accounts with a common email, stones in the same row or column.
- +In an undirected graph: count the components, or find the edge that closes a cycle.
- +Kruskal's minimum spanning tree: take an edge only if its ends are in different groups.
- +Queries sorted by a limit: add the edges under each limit, then compare roots.
Not this one when
- ×You need the actual path or its length: BFS/DFS (or Dijkstra with weights).
- ×Edges get deleted in between queries, online: union-find can't split groups.
- ×Directed graphs, "can a reach b?": reachability isn't symmetric there, so groups don't model it.
Learn Union-Find (Disjoint Set)
First, what does "union-find" mean?
Six people, 0 to 5. You keep hearing "these two are friends", and friends of friends share a group. Groups never overlap, so they're called disjoint sets. Union-find (or DSU, disjoint set union) keeps them with two operations:
- find(x): which group is x in?
- union(a, b): merge a's group and b's group into one.
Each group has one leader. Every person points to a parent, and a leader points to itself. To find your group, follow parents until someone points to themselves. Two people share a group exactly when they reach the same leader.
How do we merge groups?
Start with everyone alone, their own leader: parent = [0, 1, 2, 3, 4, 5]. The rule is one line:
To unite a and b, climb from each to its leader. If the leaders are different, make one leader point to the other. If they're the same, do nothing.
| call | leaders | what happens | parent[0..5] after |
|---|---|---|---|
| unite(0, 1) | 0, 1 | different: 1 now points to 0 | 0 0 2 3 4 5 |
| unite(2, 3) | 2, 3 | different: 3 points to 2 | 0 0 2 2 4 5 |
| unite(1, 3) | 0, 2 | 1 climbs to 0, 3 climbs to 2. Leader 2 points to 0 | 0 0 0 2 4 5 |
| unite(4, 5) | 4, 5 | 5 points to 4 | 0 0 0 2 4 4 |
| unite(5, 3) | 4, 0 | 5 climbs to 4. 3 climbs 3 → 2 → 0. Leader 0 points to 4 | 4 0 0 2 4 4 |
| unite(1, 5) | 4, 4 | 1 climbs 1 → 0 → 4, 5 climbs to 4. Same leader: nothing to do | 4 0 0 2 4 4 |
Row 3: we didn't point 3 at 1, we pointed leader 2 at leader 0. That one move brings 2's whole group along, since everyone in it climbs through 2.
The code for it
vector<int> parent; // parent[x] == x means x is a leader (a root)
int findRoot(int x) {
while (parent[x] != x) x = parent[x]; // climb until you reach the leader
return x;
}
bool unite(int a, int b) {
a = findRoot(a), b = findRoot(b);
if (a == b) return false; // same group already
parent[b] = a; // b's leader now reports to a's
return true;
}You don't need to memorise this. It's the table: climb both, compare leaders, link one under the other. unite returns false when they were already together, and that false is the part most problems use.
Why link the leaders, not a and b? In row 3, parent[1] = 3 would pull 1 out of 0's group and leave 0 behind as a separate leader. Leader to leader merges both whole groups in one step.
Fine, but how does this help us?
The classic problem: Redundant Connection. A tree on nodes 1 to n got one extra edge. Find an edge you can remove so it's a tree again (if several work, the last one in the input).
By hand: add the edges one by one, asking "were these two already connected?"
| edge | already connected? | how you know |
|---|---|---|
| 1-2 | no | nothing is connected yet |
| 2-3 | no | 3 touches nothing yet |
| 3-4 | no | 4 touches nothing yet |
| 1-4 | yes | 1 → 2 → 3 → 4 is already a path |
| 1-5 | no | 5 touches nothing yet |
1-4 joins two nodes already joined, so it closes the cycle 1-2-3-4-1. The answer is [1, 4]. (Removing 1-2, 2-3 or 3-4 would also leave a tree, but 1-4 comes last.)
The brute force
For each edge, search the edges so far: do its two ends already reach each other?
vector<int> findRedundantSlow(vector<vector<int>>& edges) {
int n = edges.size();
vector<vector<int>> adj(n + 1);
for (auto& e : edges) {
vector<bool> seen(n + 1, false);
function<bool(int)> reach = [&](int u) { // can u walk to e[1]?
if (u == e[1]) return true;
seen[u] = true;
for (int v : adj[u])
if (!seen[v] && reach(v)) return true;
return false;
};
if (reach(e[0])) return e; // already joined: extra edge
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
return {};
}It's correct, but every edge may run a DFS over everything so far: E searches of O(V + E), O(E · (V + E)). LeetCode keeps n at 1,000, so it passes there. But with 10⁵ edges, say a star of edges 1-k and then the extra one, each search walks everything so far: about 10 seconds at -O2. Time limit exceeded.
The one thought that fixes it
Stop at edge 1-4. The DFS walks 1 → 2 → 3 → 4 to prove a path exists. But we only use yes or no from that walk, never the path itself.
And "are 1 and 4 connected?" only depends on which group each is in:
- Edges are only ever added, never removed, so groups only ever merge.
- Two nodes are connected exactly when they're in the same group.
So keep the groups up to date as edges arrive, and ask "same leader?" instead. That's union-find: unite(u, v) returns false exactly when u and v were already connected: the extra edge.
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n = edges.size();
parent.resize(n + 1);
iota(parent.begin(), parent.end(), 0); // everyone starts as their own leader
rnk.assign(n + 1, 0);
for (auto& e : edges)
if (!unite(e[0], e[1])) return e; // same leader already: this edge closes a cycle
return {};
}(This uses the faster findRoot and unite below; the simple ones give the same answer.)
Dry run
parent[1..5] starts as 1 2 3 4 5.
| edge | leaders | what happens | parent[1..5] after |
|---|---|---|---|
| 1-2 | 1, 2 | different: 2 points to 1 | 1 1 3 4 5 |
| 2-3 | 1, 3 | 2 climbs to 1. Different: 3 points to 1 | 1 1 1 4 5 |
| 3-4 | 1, 4 | 3 climbs to 1. 4 points to 1 | 1 1 1 1 5 |
| 1-4 | 1, 1 | same leader: unite returns false, return [1, 4] |
1 1 1 1 5 |
[1, 4], the same answer as the brute force, without ever walking a path.
Why it's almost O(E)
The simple version's trees can grow tall: by the end of the first table, 3 climbs 3 → 2 → 0 → 4. Worse: call unite(1, 0), unite(2, 0), unite(3, 0), … Each call hangs the old leader under a new single node, so 0 ends at the bottom of a chain that every findRoot(0) climbs. For n = 10⁵: about 5 × 10⁹ steps, about 3 seconds.
Two small changes fix it:
vector<int> parent, rnk; // rnk ≈ the height of the tree under a root
int findRoot(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // path halving: jump to the grandparent
x = parent[x];
}
return x;
}
bool unite(int a, int b) {
a = findRoot(a), b = findRoot(b);
if (a == b) return false;
if (rnk[a] < rnk[b]) swap(a, b);
parent[b] = a; // the shorter tree goes under the taller one
if (rnk[a] == rnk[b]) rnk[a]++;
return true;
}- Union by rank: hang the shorter tree under the taller one. Height only grows when two equal trees meet, so a tree of rank r has at least 2ʳ nodes: with 10⁵ nodes, rank ≤ 16.
- Path halving: while climbing, point each node at its grandparent, so every
findshortens the path for next time.
On the six calls, the fast version ends with parent = [0, 0, 0, 0, 0, 0], everyone pointing straight at the leader, and on the bad chain no node is deeper than 1. Each call costs O(α(n)) amortised, and α(n) is at most 4 for any real n. So E edges cost about O(E), plus O(V) space.
From O(E · (V + E)) down to almost O(E), by asking "same group?" instead of "is there a path?".
How many groups? Count the real merges
Start with n groups of one. Every unite that returns true merges two groups, so one fewer:
int countComponents(int n, vector<vector<int>>& edges) {
parent.resize(n);
iota(parent.begin(), parent.end(), 0);
rnk.assign(n, 0);
int groups = n; // n groups of one
for (auto& e : edges)
if (unite(e[0], e[1])) groups--; // a real merge: one group fewer
return groups;
}n = 7, edges (0,1) (2,3) (1,3) (4,5) (3,0): four merges succeed, (3,0) is refused (already together), so 7 − 4 = 3 groups: {0, 1, 2, 3}, {4, 5}, {6}.
Cheapest network? Kruskal is one line on top
Sort the edges by cost and keep an edge exactly when unite returns true; an edge whose ends are already together would close a cycle. That's Kruskal's minimum spanning tree.
Remember this
- "Merge groups", "same group?", "does this edge make a cycle?" in an undirected graph → union-find.
- Always compare leaders, never the nodes, and link leader to leader.
unitereturningfalseis the signal: already connected, the edge is extra. A self-loop[u, u]is one too, so never pre-filter edges withu < v.- It only merges. If edges get deleted, it can't split: process the deletions backwards, as additions.
- Whenever a problem asks "connected?" again and again while connections keep arriving, it's this.
Practise it on Number of Provinces, then Redundant Connection (the refused edge), Graph Valid Tree (n − 1 edges, none refused), Satisfiability of Equality Equations (unite the ==, then check the !=), Accounts Merge (emails as keys) and Min Cost to Connect All Points (Kruskal).
Below, watch Number of Connected Components run line by line.
Watch it work, line by line
Number of Connected Components ↗, n = 7, edges (0,1) (2,3) (1,3) (4,5) (3,0) → 3. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Do groups only ever merge, and do I keep asking "are these two in the same group?" as connections arrive?
Reach for it when
- +dynamic connectivity with only additions
- +group equivalent items (accounts, equations)
- +detect a cycle when adding undirected edges
- +Kruskal MST
- +n, q up to 2e5-1e6
It fails when
- ×You need the actual path or distancesuse BFS/DFS or Dijkstra
- ×Groups can split (edge deletions)use Reverse offline, or DSU with rollback
- ×Directed reachability, ordering, or directed cyclesuse Topological sort / directed DFS
Looks like it, isn't (and the other way round)
- Evaluate Division looks like Graph BFS / DFS, needs this pattern
DFS per query works; weighted union-find answers each query in near O(1).
- Number of Good Paths looks like Graph BFS / DFS, needs this pattern
Process vertices by increasing value, union with neighbours of lower or equal value, and count equal-valued vertices per root (Kruskal-style).
- Is Graph Bipartite? looks like Union-Find (Disjoint Set), needs Bipartite Check / 2-Colouring
DSU with parity works, but BFS 2-colouring is the direct test.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1
unite(a, b)finds the same root for both. What does that tell you?Reveala and b are already connected, so the edge between them is redundant: it would close a cycle.
2What are the two tricks that make union-find nearly O(1) per operation?Reveal
Path compression (point nodes closer to the root while finding) and union by rank or size (hang the shorter tree under the taller).
3Why can't union-find handle edge deletions directly, and what's the workaround?Reveal
Merging is one pointer write, but splitting a group would need to know which nodes went where. Process the deletions backwards as additions.
Practice ladder
- 1Number of Provincescount groupsMedium
- 2Number of Connected Components in an Undirected Graphthe hookMedium
- 3Redundant Connectionthe redundant edgeMedium
- 4Graph Valid Treethe redundant edgeMedium
- 5Satisfiability of Equality Equationsequal first, then checkMedium
- 6Accounts Mergekeys instead of indicesMedium
- 7Most Stones Removed with Same Row or Columnkeys instead of indicesMedium
- 8Checking Existence of Edge Length Limited Pathsqueries sorted by a limitHard
Finished Union-Find (Disjoint Set)? Mark it done and Lessgo moves you to the next step.