Skip to content
Data structures

What is union find and when should you use it

What is union find? It is a structure that tracks which items share a group, with near-constant amortized cost for merging groups and checking membership. Here is how it works, why it is fast, and when it beats BFS or DFS.

What is union find? It is a data structure that tracks which items belong to the same group, supporting two operations: merge two groups and ask whether two items share a group. With union by size and path compression, each operation costs near-constant amortized time, so it beats re-running a graph search after every change.

I reach for it less often than a hash map or a heap, but when the problem fits, nothing else comes close. The trouble is that the fit is easy to miss. The problem rarely says "disjoint sets". It says "are these two accounts the same person", or "does adding this edge create a cycle", or "how many islands exist after this cell turns to land". This essay explains the structure, walks one example with real numbers, and gives you a test for when to use it.

What problem does union find actually solve?

It solves dynamic connectivity in its simplest form: you have n items, groups only ever merge (never split), and you need to answer "same group?" quickly while the merging is still going on. That one-directional restriction is the whole point. Because groups never split, you can keep a very cheap summary of each group instead of the full graph.

Here is the analogy I use. Imagine a company where every employee carries a sticky note naming the person they think is in charge. Most notes name a direct manager, who has a note of their own, and so on up to someone whose note names themselves: the head of that company. To check whether two people work for the same company, you chase each person's notes upward and compare the two people at the top. A merger is a single act: the head of one company writes the other head's name on their note. Nothing else changes. The expensive part is chasing long chains, and the two optimisations later in this essay are really two ways of keeping those chains short: be careful about who reports to whom, and cross out old chains the moment you have walked them.

Compare that with the naive alternative. Suppose you store the graph as adjacency lists and answer each "are these connected" query with a BFS or DFS. One query costs O(n + m). If you have 1,000,000 nodes, about 2,000,000 edges, and 200,000 queries interleaved with edge insertions, that is roughly 3,000,000 steps per query, or 6 x 1011 steps total. Far too slow for any judge or production service. A union find answers the same 200,000 queries in a few million steps altogether.

How does union find work, step by step?

Each item stores a parent pointer, and the root of a tree is the item whose parent is itself. A find walks up to the root; a union finds two roots and hooks one under the other. Two items are in the same group exactly when their finds return the same root.

Two arrays carry everything. parent[i] starts as i, so every item is its own group. size[i] starts as 1 and is only meaningful at roots. Here is a complete version that I would be comfortable writing on a whiteboard:

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.groups = n

    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:
            self.parent[x], x = root, self.parent[x]
        return root

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        self.groups -= 1
        return True

Three details are worth stating plainly. First, find is iterative on purpose. A recursive find on a chain of 100,000 nodes will blow Python's default recursion limit of 1,000, and in other languages it can overflow the stack. Second, union returns a boolean saying whether it actually merged anything. That return value is what makes cycle detection a one-liner: if you try to union two items that already share a root, the edge you are adding closes a cycle. Third, groups is a free counter. Every successful union reduces the number of groups by exactly one, so you never need to scan for roots at the end.

Why do union by size and path compression matter?

Without them, a find can cost O(n); with both, the amortized cost per operation is O(α(n)), where α is the inverse Ackermann function, which never exceeds 4 for any input that could fit in memory. Each trick alone gets you most of the way, and together they get you the rest.

Start with the failure case. If union always hooks the first root under the second, then unioning (0,1), (1,2), (2,3) and so on can build a straight line: item 0 points at 1, which points at 2, and so on. A find on item 0 in a chain of 1,000,000 items walks 1,000,000 pointers. Run that find 1,000,000 times and you have done 1012 steps, which is no better than the graph search.

Union by size fixes the shape. Always hook the smaller tree under the larger. A node's depth only increases when its tree is hooked under a tree at least as big, which means its tree's size at least doubles. Sizes cannot double more than log2(n) times before they hit n, so no node ever has depth above log2(n). For n = 1,000,000 that bounds every find at about 20 pointer hops. This is a real guarantee, not an average: it holds in the worst case.

Path compression repairs the shape as you use it. After a find walks from x up to the root, it rewrites every pointer on that path to point straight at the root. The first find through a deep chain pays for the whole chain, but every later find through any node on that chain pays one hop. In the sticky note picture, you cross out the long chain of managers and write the head's name directly. Proving the tight bound of O(α(n)) is a genuine piece of analysis (Tarjan's), and I will not pretend to reproduce it here. What you can verify yourself is the weaker and still useful claim: with path compression alone, m operations on n items cost O(m log n) amortized. If the word amortized is hazy, this essay on amortized time complexity covers the idea.

In practice I always write both. Union by size costs one extra array and two lines; compression costs one extra loop. Skipping either to save typing is a bad trade.

What does a worked example look like with real numbers?

Take 8 items numbered 0 to 7, the code above, and these unions in order: (0,1), (2,3), (1,3), (4,5), (6,7), (5,7), (3,7). I will write the parent array after each step, with ties broken by keeping the first argument's root on top.

  • Start: parent = [0,1,2,3,4,5,6,7], 8 groups.
  • union(0,1): equal sizes, so 1 goes under 0. parent = [0,0,2,3,4,5,6,7], size[0] = 2, 7 groups.
  • union(2,3): 3 goes under 2. size[2] = 2, 6 groups.
  • union(1,3): find(1) = 0, find(3) = 2, both size 2. Root 2 goes under 0. size[0] = 4, 5 groups.
  • union(4,5): 5 goes under 4. 4 groups.
  • union(6,7): 7 goes under 6. 3 groups.
  • union(5,7): find(5) = 4, find(7) = 6. Root 6 goes under 4. size[4] = 4, 2 groups.
  • union(3,7): find(3) walks 3, 2, 0. find(7) walks 7, 6, 4. Both trees have size 4, so root 4 goes under 0. size[0] = 8, 1 group.

The final array is [0,0,0,2,0,4,4,6]. Item 7 now sits at depth 3 (7 to 6 to 4 to 0), and log2(8) = 3. That is the worst case the bound allows, and I chose the order to reach it. Now call find(7). The first loop walks three hops to find root 0. The second loop rewrites parent[7] and parent[6] to 0; parent[4] was already 0. The array becomes [0,0,0,2,0,4,0,0]. The next find(7) costs one hop instead of three.

Now scale it. Suppose a 1000 by 1000 grid where each land cell must be merged with its right and down neighbours. That is 106 cells and about 2 x 106 union calls. Each union does two finds, each bounded by about 20 hops with size alone and typically 1 to 3 after compression. So the total is on the order of 4 x 106 to 8 x 107 pointer reads in the worst case, and usually near the low end. A Python implementation of this runs in a couple of seconds; the same logic in a compiled language finishes in tens of milliseconds. That is the profile of a problem where union find is comfortable, not heroic.

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

Use union find when connections arrive over time and you must answer connectivity questions between arrivals; use BFS or DFS when you have the whole graph up front and need paths, distances, or one full pass of labelling. The deciding question is whether the answer to "are these connected" needs to be fresh after each new edge.

If the graph is static and you only need component counts, a single DFS is just as fast, simpler, and carries no extra arrays. The classic Number of Islands is exactly this: one pass over a grid. Union find solves it too, but it is not better, and I would say so in an interview. Where union find pulls ahead is when the problem is online. A variant of that problem where land cells appear one at a time and you must report the island count after each addition forces a DFS solution to recompute from scratch, while union find just does one cell's worth of unions and reads the groups counter.

The table below compares the realistic options for connectivity questions on n nodes with m edges and q queries.

ApproachCost per queryCost per edge addedBest when
BFS or DFS per queryO(n + m)O(1) (append to adjacency list)Few queries, need the actual path
Relabel all components after each edgeO(1)O(n)Many queries, almost no edges
Union find, no optimisationsO(n) worst caseO(n) worst caseNever, on purpose
Union find, size onlyO(log n)O(log n)Fine when you cannot afford compression
Union find, size and compressionO(α(n)) amortizedO(α(n)) amortizedInterleaved merges and queries

Notice the first two rows are mirror images: one pays at query time, the other at update time. Union find is the structure that stops paying either bill in full. If you want the traversal side of the decision in more detail, when to use BFS vs DFS covers it.

These are the patterns where I have seen it earn its place:

  • Kruskal's minimum spanning tree. Sort edges by weight, and keep an edge only if its endpoints are in different groups. Sorting costs O(m log m); the union find work is nearly linear on top of that.
  • Cycle detection in an undirected graph. Process edges one at a time; the first union that returns False closes a cycle.
  • Merging by shared attribute. Accounts that share an email, users that share a device, words linked by a synonym pair. Each shared attribute becomes a union.
  • Equivalence constraints. Statements like a == b and b == c, followed by a != c. Union all the equalities first, then check every inequality for a shared root.
  • Redundant connection problems. Find the edge whose addition first creates a cycle.

What can union find not do?

It cannot split a group, it cannot tell you the path between two items, and it knows nothing about direction or edge weights beyond what you bolt on. Every one of these limits follows from the thing that makes it fast: it forgets the original edges.

The no-deletion rule bites hardest. If a problem removes edges, the standard trick is to run time backwards: start from the final graph, process the removals in reverse as additions, and record answers in reverse. That works when all operations are known in advance. When they are not, you need a heavier structure such as a link-cut tree, and at that point you are well past interview territory.

Directed graphs are a second trap. Union find answers "are a and b in the same undirected component", which for directed graphs is weak connectivity, not reachability. For "can I get from a to b" or for ordering tasks like Course Schedule, you need a traversal or a topological sort. I have watched candidates reach for union find on that problem because "it is about connected things", and it quietly gives wrong answers.

Third, compression destroys the tree shape, so you cannot read structure out of the parent array afterwards. If you need to enumerate the members of each group, keep a separate pass: loop over all items, call find, and bucket by root. That costs O(n α(n)) once, which is fine.

Frequently asked questions

Is union find the same as disjoint set union?

Yes. Union find, disjoint set union (DSU) and disjoint set forest are different names for the same structure. The first name describes the two operations; the others describe what it represents.

Why is the complexity inverse Ackermann and not just O(1)?

Because the proven bound really does grow, just absurdly slowly. The inverse Ackermann function is at most 4 for any n you could ever store, so calling it constant is fine for engineering, but the strict statement is O(α(n)) amortized per operation.

Do I need both union by size and path compression?

You can pass most interviews with either one, since size alone bounds a find at log n and compression alone gives O(log n) amortized. I still write both, because together they cost about five extra lines and remove any argument about worst cases.

If you want to practise the pattern on something concrete, start with the grid-merging idea in Number of Islands, solve it once with DFS and once with the DSU class above, and compare how each handles the extra requirement of reporting the count after every new land cell.