Union-Find (disjoint set union) explained

Union-Find, also called a disjoint set union, keeps track of which items belong to the same group while new links keep arriving. Each group is a tree whose root names the group; find walks to the root and union hangs one root under the other. With union by size and path compression, a long run of operations costs close to constant time per operation, which makes it the standard tool for connectivity, cycle detection and Kruskal's algorithm.

By Published 9 min read

The task, restated

A help desk has n tickets numbered 0 to n - 1. An agent reviews them and produces pairs like (2, 7), meaning tickets 2 and 7 came from the same customer. Sameness spreads: if 2 matches 7 and 7 matches 9, then 2 and 9 are one customer too, even though nobody compared them directly. You are asked for the number of distinct customers once every pair is applied. A second question follows quickly in most interviews: while the pairs are applied in order, which is the first pair that told you nothing new, because its two tickets were already linked?

Examples made up for this page
nPairs, in orderCustomersFirst redundant pair
6(0,1) (2,3) (1,2) (4,5) (0,3)2(0,3), since 0-1-2-3 already joins them
4none4none
5(0,1) (1,2) (2,3) (3,4)1none, every pair merges two groups
3(1,1) (0,2)2(1,1), a ticket matched with itself
1none1none
Examples made up for this page. Scroll sideways on a small screen.

Before coding, ask three things. Are ticket ids always 0 to n - 1, or arbitrary strings that need a lookup table first? Can a pair repeat or point an item at itself? And are the pairs known up front, or do they stream in with questions mixed between them? The last answer decides whether Union-Find is needed at all.

Where it turns up in interviews

Interviewers use Union-Find as a check on whether you know one structure beyond arrays, maps and heaps, and whether you can say why it is fast. The structure itself is about fifteen lines, so the grading leans on judgment: picking it over BFS for the right reason, naming the two optimizations, and adapting it when the task changes shape. Common shapes include:

  • Count groups after all links are known. Friend circles, connected computers, provinces. BFS or DFS also works here.
  • Links arrive over time, with questions between them. Are a and b connected right now? How many groups are left? This is where Union-Find wins clearly.
  • Find the edge that closes a cycle in an undirected graph. The first pair whose ends already share a root is the answer.
  • Merge records by a shared field. Group email accounts that share any address, by joining each address to the first account that listed it.
  • Build a minimum spanning tree with Kruskal. Sort edges by cost and keep an edge only when union succeeds, as on Min Cost to Connect All Points.

A slow baseline: relabel on every merge

The first idea most people have is a label per ticket. Start with label[i] = i. To merge a pair, take the second ticket's label and rewrite every ticket carrying it to the first ticket's label. Counting distinct labels at the end gives the answer. It is correct, but each merge scans the whole array, so m pairs cost O(n times m). With a hundred thousand tickets and as many pairs, that is billions of steps.

def count_customers_slow(n, pairs):
    label = list(range(n))
    for a, b in pairs:
        old, new = label[b], label[a]
        if old != new:
            for i in range(n):
                if label[i] == old:
                    label[i] = new
    return len(set(label))
Relabelling baseline. Correct, quadratic in the worst case.

Be fair to graph search here. If all pairs are known before any question, you can build an adjacency list and count components with BFS or DFS in O(n + m), which is already optimal. Say so in the interview. Union-Find is the better choice when merges and questions interleave, because rebuilding a search after every new pair is expensive, and it is often simpler to write than an adjacency list when all you need is the count.

How the structure works

Every ticket stores a parent, called boss in the code below. A ticket whose boss is itself is a root, and the root's id is the name of the whole group. find(x) follows bosses until it reaches a root. join(a, b) finds both roots; if they match, the tickets were already in one group and nothing changes; otherwise one root becomes the boss of the other and the group count drops by one.

Left alone, the trees can turn into long chains, and find becomes linear. Two changes stop that. Union by size always hangs the smaller tree under the larger one, so a ticket's depth grows only when its group at least doubles, which caps depth at about log2 of n. Path compression rewires tickets to point closer to the root while find walks up. The version below uses path halving: each visited ticket skips to its grandparent, which needs no recursion and no second pass.

Optimal approach: union by size with path halving

class Groups:
    def __init__(self, n):
        self.boss = list(range(n))
        self.size = [1] * n
        self.count = n

    def find(self, x):
        while self.boss[x] != x:
            self.boss[x] = self.boss[self.boss[x]]  # skip to grandparent
            x = self.boss[x]
        return x

    def join(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.boss[rb] = ra
        self.size[ra] += self.size[rb]
        self.count -= 1
        return True


def count_customers(n, pairs):
    groups = Groups(n)
    for a, b in pairs:
        groups.join(a, b)
    return groups.count


def first_redundant(n, pairs):
    groups = Groups(n)
    for a, b in pairs:
        if not groups.join(a, b):
            return (a, b)
    return None
Python: the structure plus the two questions from the task.
class DisjointSets {
  constructor(n) {
    this.parent = new Int32Array(n);
    this.weight = new Int32Array(n).fill(1);
    for (let i = 0; i < n; i++) this.parent[i] = i;
    this.groups = n;
  }

  find(x) {
    while (this.parent[x] !== x) {
      this.parent[x] = this.parent[this.parent[x]];
      x = this.parent[x];
    }
    return x;
  }

  union(a, b) {
    let ra = this.find(a);
    let rb = this.find(b);
    if (ra === rb) return false;
    if (this.weight[ra] < this.weight[rb]) [ra, rb] = [rb, ra];
    this.parent[rb] = ra;
    this.weight[ra] += this.weight[rb];
    this.groups -= 1;
    return true;
  }
}

function countCustomers(n, pairs) {
  const sets = new DisjointSets(n);
  for (const [a, b] of pairs) sets.union(a, b);
  return sets.groups;
}

function firstRedundant(n, pairs) {
  const sets = new DisjointSets(n);
  for (const [a, b] of pairs) {
    if (!sets.union(a, b)) return [a, b];
  }
  return null;
}
JavaScript: typed arrays keep the parent and size tables compact.

join returning a boolean is the small design choice that pays off. The count, the redundant pair and Kruskal's edge test all read that one return value, so you never call find twice from the outside.

Trace on the first example

n = 6, pairs (0,1) (2,3) (1,2) (4,5) (0,3), with the code above
PairRoots foundActionboss array afterGroups
start[0, 1, 2, 3, 4, 5]6
(0,1)0 and 1equal sizes, 1 goes under 0[0, 0, 2, 3, 4, 5]5
(2,3)2 and 33 goes under 2[0, 0, 2, 2, 4, 5]4
(1,2)0 and 2sizes 2 and 2, 2 goes under 0[0, 0, 0, 2, 4, 5]3
(4,5)4 and 55 goes under 4[0, 0, 0, 2, 4, 4]2
(0,3)0 and 0same root, returns false[0, 0, 0, 0, 4, 4]2
n = 6, pairs (0,1) (2,3) (1,2) (4,5) (0,3), with the code above. Scroll sideways on a small screen.

Look at the last row. Finding the root of 3 walked 3 to 2 to 0, and path halving rewired 3 to point straight at 0 on the way. Nothing merged, but the next find on 3 is one step shorter. That quiet repair is why the amortized cost stays tiny.

Time and space

Cost for n items and m operations
VersionCost per operationExtra space
Relabel every mergeO(n) per mergeO(n)
BFS once, all pairs knownO(n + m) totalO(n + m) adjacency list
Plain parent pointersO(n) worst caseO(n)
Union by size onlyO(log n) worst caseO(n)
Path compression onlyO(log n) amortizedO(n)
Both togetherO(α(n)) amortized, α is the inverse Ackermann functionO(n)
Cost for n items and m operations. Scroll sideways on a small screen.

The inverse Ackermann function grows so slowly that it stays below 5 for any input you could store, so people often say near-constant time. If an interviewer asks you to prove it, it is fine to say the proof is long and well known (Tarjan's analysis) and explain the intuition instead: size ranking keeps trees shallow, and compression flattens whatever depth is left.

Edge cases

  • No pairs: the answer is n, and there is no redundant pair.
  • A pair (x, x): both finds return the same root, so join returns false. Decide with the interviewer whether that counts as redundant; the code above treats it as redundant.
  • Duplicate pairs: the second copy is always redundant.
  • Ids that are strings or large numbers: map each new id to the next free index with a dictionary first, then run the same code.
  • One giant chain of pairs: union by size keeps the trees shallow, and the find loop is iterative, so there is no recursion depth issue in Python.

Mistakes to avoid

  • Setting boss[a] = b instead of boss[root of a] = root of b. That cuts a out of its old group and corrupts the count.
  • Comparing boss[a] == boss[b] to test connection. Two items can share a root without sharing a direct parent; always compare find results.
  • Adding sizes to the wrong root after swapping, so the size table drifts away from reality.
  • Writing find recursively in Python for very deep chains without union by size, which can hit the recursion limit.
  • Decrementing the group count even when the two roots were already equal.
  • Reaching for Union-Find on a directed graph. It models undirected sameness; directed cycle detection needs DFS colors or a topological sort.

How to explain it out loud

Fictional example

Explaining the choice before the code
Candidate
If every pair were known up front I could build a graph and count components with BFS in linear time. Since you said pairs arrive while you keep asking for the count, I'll use a disjoint set union instead.
Candidate
Each ticket points at a parent, and a root names its group. Join finds both roots, and if they differ I hang the smaller tree under the bigger one and drop the count by one.
Candidate
Find does path halving, so the trees stay flat. With both tricks, each operation is effectively constant amortized, inverse Ackermann if you want the exact bound. And join returning false is exactly the redundant pair you asked about.

Dijkstra's algorithm is the other graph tool worth having ready: it answers how far, while Union-Find answers whether connected. Decode String looks unrelated, yet it rewards the same habit of naming your state before you write the loop. Number of Islands can be solved with Union-Find over grid cells as well as with flood fill, and comparing the two is a good exercise. Min Cost to Connect All Points uses the structure inside Kruskal's algorithm.

Practicing with Natively

During a practice session on a Mac or Windows PC, Natively can capture a problem like this from your screen and lay out an approach and code next to yours, and its Code hint action gives a coding hint when you are stuck. It also keeps a transcript of what you said, which makes it easy to check whether you justified Union-Find over BFS before you started. Setup notes live on the AI interview assistant page.

Questions people ask

What is Union-Find used for in coding interviews?

It answers whether two items are in the same group while new links keep arriving. Typical uses are counting connected groups, finding the edge that closes a cycle in an undirected graph, merging records that share a field, and Kruskal's minimum spanning tree.

What are union by size and path compression?

Union by size hangs the smaller tree under the larger root so trees stay shallow. Path compression, or its loop-friendly cousin path halving, points nodes closer to the root during find. Together they make each operation nearly constant time amortized.

What is the time complexity of Union-Find?

With both optimizations, m operations on n items take O(m α(n)) time, where α is the inverse Ackermann function and is below 5 for any practical n. Space is O(n) for the parent and size arrays.

When should I use BFS instead of Union-Find?

If every link is known before any question, BFS or DFS counts components in O(n + m) and is just as good. Union-Find wins when links and connectivity questions are mixed together over time.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP