Union-Find

In short: Union-find, also called a disjoint set union (DSU), is a data structure that keeps track of items split into non-overlapping groups: find tells you which group an item is in, and union merges two groups. With path compression and union by size or rank, both take O(α(n)) amortized time, where α is the inverse Ackermann function, which is nearly constant. It's used for connected components, cycle detection in undirected graphs, and Kruskal's algorithm.

Quick reference

Union-find (also called a disjoint set union, or DSU) is a data structure that keeps track of items split into non-overlapping groups. It does two things quickly: find tells you which group an item is in, and union merges two groups into one.

How it works:

  • Each group is a tree. Every item points to a parent, and the item at the top of the tree (the root) names the group.
  • find(x) follows parent pointers up to the root. Two items are in the same group if they have the same root.
  • union(a, b) finds both roots and points one at the other.

Two tricks keep it fast:

  • Path compression: after a find, point every item it passed straight at the root.
  • Union by size (or by rank): always put the smaller tree under the bigger one.

Cost:

  • With both tricks, find and union take O(α(n)) amortized time, where α is the inverse Ackermann function. That's at most 4 for any input that could fit in memory, so it's nearly constant, but it isn't O(1). Space is O(n).

How Union-Find Works

Say six bakeries, numbered 0 through 5, start out as independent businesses. Over time, some of them merge into bigger companies, and we want to answer questions like "are bakeries 1 and 5 owned by the same company now?"

Union-find stores who reports to whom in a array called parent. Think of parent[x] as the bakery that bakery x reports to:

  • At the start, every bakery reports to itself: parent[x] == x. A bakery that reports to itself is a root, the headquarters of its company.
  • find(x) follows the chain of "reports to" links from x until it reaches a headquarters, and returns it. Two bakeries are in the same company exactly when they have the same headquarters.
  • union(a, b) finds the headquarters of a and of b. If they're different, it makes one headquarters report to the other, which merges the two companies.

That's all it takes to be correct. But if we link roots carelessly, a company can turn into one long chain, like 5 → 4 → 3 → 2 → 1 → 0, and every find from the bottom has to walk the whole thing: O(n) time. Two tricks prevent that.

Union by size (or rank)

When merging, make the smaller group's root report to the bigger group's root, and keep a count of each group's size at its root. An item only gets one step farther from its root when its group joins a group at least as big, so its group at least doubles in size every time that happens. A group can't double more than log2 n times, so no tree ever gets taller than log2 n, and find takes O(log n) time even without the second trick.

Union by rank does the same thing with a different number. Each root keeps a rank, an upper bound on its tree's height. The root with the lower rank goes under the one with the higher rank, and if they're tied, either one can go on top and its rank goes up by 1. Both give the same guarantees. Size is handy when you also want to know how big each group is.

Path compression

Once find(x) has walked up to the root, it already knows the answer for every item it passed along the way. So it makes a second pass and points each of them directly at the root. The next find on any of those items takes one step. Trees get flatter every time you use them.

Union-Find Example, Step by Step

Here's the parent array for our six bakeries as the mergers happen. We use union by size, and when two groups are the same size, the second root goes under the first.

Step Operation What happens parent (items 0 to 5) Groups
Start Every item is its own root. [0, 1, 2, 3, 4, 5] {0} {1} {2} {3} {4} {5}
1 union(0, 1) Roots 0 and 1 have the same size, so 1 goes under 0. [0, 0, 2, 3, 4, 5] {0, 1} {2} {3} {4} {5}
2 union(2, 3) Same size, so 3 goes under 2. [0, 0, 2, 2, 4, 5] {0, 1} {2, 3} {4} {5}
3 union(1, 3) find(1) is 0 and find(3) is 2. Both groups have 2 items, so root 2 goes under root 0. [0, 0, 0, 2, 4, 5] {0, 1, 2, 3} {4} {5}
4 union(4, 5) Same size, so 5 goes under 4. [0, 0, 0, 2, 4, 4] {0, 1, 2, 3} {4, 5}
5 union(5, 3) find(5) is 4. find(3) walks 3 → 2 → 0, and path compression points 3 straight at 0. Root 4's group (2 items) is smaller than root 0's (4 items), so 4 goes under 0. [0, 0, 0, 0, 0, 4] {0, 1, 2, 3, 4, 5}
6 find(5) Walks 5 → 4 → 0, returns 0, and points 5 straight at 0. [0, 0, 0, 0, 0, 0] {0, 1, 2, 3, 4, 5}

After step 4, asking whether bakeries 1 and 5 are connected means comparing find(1), which is 0, with find(5), which is 4. They're different, so the answer is no. After step 5, both finds return 0.

Notice that parent[3] was 2 after step 3, even though 3's group was named by root 0. Only find tells you an item's group. A parent entry on its own doesn't.

Union-Find Implementation

Here's union-find with path compression and union by size. Items are numbered 0 to n - 1. We also keep a count of how many groups there are, which goes down by one every time a union actually merges two groups. The example at the bottom runs the same steps as the table above:

public class UnionFind { private final int[] parent; // parent[x] == x means x is a root private final int[] size; // size[root] is how many items are in root's group private int count; // how many groups there are // items are numbered 0 to n - 1, and each starts in its own group public UnionFind(int n) { parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } count = n; } public int find(int x) { // follow parent links up to the root, which names x's group int root = x; while (parent[root] != root) { root = parent[root]; } // path compression: point every item we passed straight at the root while (parent[x] != root) { int nextItem = parent[x]; parent[x] = root; x = nextItem; } return root; } public boolean union(int a, int b) { int rootA = find(a); int rootB = find(b); if (rootA == rootB) { return false; // already in the same group } // union by size: put the smaller group's root under the bigger one's if (size[rootA] < size[rootB]) { int temp = rootA; rootA = rootB; rootB = temp; } parent[rootB] = rootA; size[rootA] += size[rootB]; count--; return true; } public boolean connected(int a, int b) { return find(a) == find(b); } public int getCount() { return count; } } // UnionFind uf = new UnionFind(6); // uf.union(0, 1); // uf.union(2, 3); // uf.union(1, 3); // uf.union(4, 5); // uf.getCount() is 2, uf.connected(1, 3) is true, and uf.connected(1, 5) is false // uf.union(5, 3); // uf.find(5) is 0

union returns whether it merged two different groups. That one bit of information is what powers cycle detection and Kruskal's algorithm below.

If your items aren't numbered 0 to n - 1 (they're strings, say, or grid coordinates), either give each one a number with a hash map first, or store parent and size in hash maps and add each item the first time you see it.

Union-Find Time and Space Complexity

How fast union-find is depends on which tricks you use. Here n is the number of items, and "amortized" means averaged over a long sequence of operations:

Version find and union, amortized One find, worst case
Neither trick O(n) O(n)
Union by size or rank only O(log n) O(log n)
Path compression only O(log n) O(n)
Both O(α(n)) O(log n)

Setting up the structure takes O(n) time, and it uses O(n) space for the parent and size arrays.

What's the inverse Ackermann function?

The Ackermann function is a function that grows absurdly fast, much faster than 2^n or even towers of powers of 2. Its inverse, written α(n), grows just as absurdly slowly. It's at most 4 for every n up to a number far bigger than the number of atoms in the observable universe.

So with both tricks, any long sequence of finds and unions costs at most a small constant number of steps each, on average. Two things keep it from being a true O(1):

  • α(n) does keep growing as n grows. It just grows so slowly that you'll never see it.
  • It's an amortized bound. A single find can still take O(log n) steps. It's the average over many operations that's nearly constant, because each slow find flattens the tree for the finds after it.

In an interview, "O(α(n)) amortized, which is nearly constant" is the precise answer. If you only implement one trick, the safe answer is O(log n).

What Union-Find Is Used For

Connected components and cycle detection

To count the connected components in an undirected graph, start with every node in its own group and union the two ends of every edge. The number of groups left is the number of components.

An undirected graph has a cycle exactly when some edge connects two nodes that are already connected. So if union ever returns false, that edge closes a loop:

public static int countComponents(int n, int[][] edges) { UnionFind uf = new UnionFind(n); for (int[] edge : edges) { uf.union(edge[0], edge[1]); } return uf.getCount(); } public static boolean hasCycle(int n, int[][] edges) { UnionFind uf = new UnionFind(n); for (int[] edge : edges) { // if the two ends are already connected, this edge closes a loop if (!uf.union(edge[0], edge[1])) { return true; } } return false; } // countComponents(5, new int[][] {{0, 1}, {1, 2}, {3, 4}}) returns 2 // hasCycle(4, new int[][] {{0, 1}, {1, 2}, {2, 3}}) returns false // hasCycle(4, new int[][] {{0, 1}, {1, 2}, {2, 3}, {3, 1}}) returns true

Both take O(V + E · α(V)) time for V nodes and E edges, and they never need to build an adjacency list.

Kruskal's algorithm

Kruskal's algorithm finds a minimum spanning tree by going through the edges from cheapest to most expensive and keeping each edge that doesn't create a cycle. That's exactly the check above: if union(a, b) returns true, the edge joins two different trees, so keep it. If it returns false, skip it. Sorting the edges takes O(E log E) time, and all the unions and finds together are nearly linear, so the sort is the slow part.

Grouping equivalent items

Any time a problem says "if A matches B and B matches C, then A matches C," union-find can build the groups. For example, in "accounts merge," each account is a list of email addresses, and two accounts belong to the same person if they share any address. Number the addresses with a hash map, union every address in an account with the account's first address, then group the addresses by their root. The same trick handles "are these equations consistent?" problems: union everything that's ==, then check that no != pair ended up in the same group.

Counting islands

You can count the islands in a grid of land and water without BFS or DFS. Give each cell its own number, row * width + col. For each land cell, union it with the land cell to its right and the land cell below it. The number of islands is the number of land cells minus the number of unions that actually merged two groups. For a single grid, BFS and DFS work just as well. Union-find pulls ahead in the version where land is added one cell at a time and you need the island count after every addition.

Union-Find vs. BFS and DFS

Breadth-first and depth-first search can answer the same connectivity questions. Which one to use depends on how the graph shows up:

Union-find BFS or DFS
Best when Edges arrive over time, and you need to answer "connected?" or "how many groups?" in between The whole graph is known up front, and you explore it once
Time O(α(V)) amortized per edge or query O(V + E) per search, which you'd have to redo after every new edge
Memory O(V). It doesn't need to store the edges at all. O(V + E) for the adjacency list, plus O(V) for the visited set
Can it give you a path? No. It only knows whether two items are connected. Yes. BFS even finds the shortest path in an unweighted graph.
Deleting edges Not supported. There's no way to split a group back apart. Just search the updated graph again
Directed graphs No. It only tracks undirected connectivity. Yes: reachability, directed cycles, topological sort

The short version: use union-find when connections only get added and you keep asking who's connected to whom. Use BFS or DFS when you need paths, distances, or edge directions, or when edges can be removed.

Common Union-Find Mistakes

  • Comparing parent entries instead of roots. In the example, after step 3, parent[1] is 0 and parent[3] is 2, but 1 and 3 are in the same group. Always compare find(a) with find(b).

  • Linking the items instead of their roots. Writing parent[a] = b moves a (and everything under it) out of its old group, so the rest of that group is no longer connected to it. Always find both roots and link one root to the other.

  • Updating the wrong size. Sizes only mean something at roots. After putting rootB under rootA, add rootB's size to rootA's, not the other way around.

  • Using it on a directed graph. With edges 0 → 1, 0 → 2, and 1 → 2, there's no directed cycle, but the third union finds 1 and 2 already connected and reports one. For directed graphs, use a DFS or topological sort instead.

  • Listing each undirected edge twice. If you build the edge list from an adjacency list, the edge between a and b shows up as both (a, b) and (b, a), and the second copy looks like a cycle. Only process each edge once.

  • Expecting to undo a union. Union-find can't delete an edge or split a group. If you know all the deletions ahead of time, a common trick is to process the operations in reverse order, so deletions become additions. Otherwise, use a graph search.

  • A recursive find on a tall tree. The popular one-line recursive find is fine with union by size, since trees stay at most log2 n tall. Without union by size, a long chain can overflow the call stack (Python's default recursion limit is 1,000). The two-loop find above avoids recursion entirely.

Classic Union-Find Problems

  • Number of connected components (or "number of provinces"): union every edge, then return the group count.
  • Redundant connection: find the edge that turns a tree into a graph with a cycle. It's the first edge whose union returns false.
  • Graph valid tree: n nodes form a tree if there are exactly n - 1 edges and every union succeeds.
  • Accounts merge and other "group the equivalent items" problems.
  • Number of islands II: land is added one cell at a time, and you report the island count after each addition.
  • Satisfiability of equality equations: union the == pairs, then check the != pairs.
  • Minimum spanning tree with Kruskal's algorithm.

Frequently Asked Questions

What is union-find?

Union-find, also called a disjoint set union or DSU, is a data structure that keeps track of items split into non-overlapping groups. Its find operation tells you which group an item is in, and its union operation merges two groups.

How does union-find work?

Each group is stored as a tree in a parent array, and the root of each tree names the group. Find follows parent pointers up to the root, and union finds both roots and points one at the other.

What are path compression and union by rank?

Path compression makes every item a find passes point straight at the root, which flattens the tree. Union by rank (or by size) always puts the shorter or smaller tree under the other one, which keeps every tree at most log n tall.

What is the time complexity of union-find?

With both path compression and union by rank or size, find and union take O(α(n)) amortized time, where α is the inverse Ackermann function. α(n) is at most 4 for any input that fits in memory, so it's nearly constant, but it isn't O(1). With only one of the two tricks, it's O(log n) amortized.

When should you use union-find instead of BFS or DFS?

Use union-find when edges arrive over time and you need to check connectivity or count groups in between, since each new edge takes nearly constant time instead of a whole new search. Use BFS or DFS when you need paths or distances, when the graph is directed, or when edges can be deleted.

How do you detect a cycle with union-find?

Union the two ends of each edge in an undirected graph. If the two ends already have the same root, they were already connected, so that edge closes a cycle. This only works for undirected graphs, and each edge should be processed once.

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .