Union-Find

How union-find tracks groups that merge over time, why union by size and path compression make it fast, and what interviewers ask about it.

14 minLesson 1 of 4
On this page
  1. How union-find works
  2. Keeping the trees shallow
  3. Code
  4. Variants and limits
  5. In the interview
  6. What to practise next

Union-find, also called a disjoint-set union, is a data structure that keeps track of which items belong to the same group. It supports two operations: union merges two groups, and find tells you which group an item is in, so you can check whether two items are in the same group. You reach for it when groups only ever merge and you need to ask "are these two connected?" many times between merges.

Without it, every question needs a BFS or DFS over the graph built so far, which costs O(V + E) per question. With 100,000 items and 100,000 questions that is billions of steps. Union-find does not store paths, only the group of each item, and answers each question in close to constant time.

How union-find works

Every group is stored as a tree, and the item at the top of the tree is the group's root. Each item stores its parent in an array. A root is its own parent, so at the start every item is a root of a group of one.

  • find(x) follows parent pointers from x until it reaches an item that is its own parent, and returns that root. Two items are in the same group exactly when find returns the same root for both.
  • union(a, b) calls find on both items. If the roots are different, it makes one root the parent of the other. That single pointer change merges the two groups, because every other member still leads to its old root, and that root now leads to the new one.

The trace below uses six computers numbered 0 to 5 and connects them with cables one at a time. Cell i of parent holds the parent of computer i, and arrows in the picture point from each computer to its parent. Each root also stores a size, the number of computers in its group, which the next section explains.

Plug in cables and merge groupsUse the arrows or ← → keys
find(x):  if parent[x] != x: parent[x] = find(parent[x])  return parent[x]union(a, b):  ra, rb = find(a), find(b)  if ra == rb: return false  if size[ra] < size[rb]: swap ra, rb  parent[rb] = ra; size[ra] += size[rb]
  1. parent
    00
    11
    22
    33
    44
    55
    012345
    groups
    6

    1Before any connection, parent[i] = i for every computer, so each one is its own group of size 1.

  2. parent
    00
    10
    22
    33
    44
    55
    012345
    groups
    5
    size[0]
    2

    2Connect 0 and 1. Both roots have size 1, which is a tie, so ra stays 0 and 1 becomes a child of 0.

  3. parent
    00
    10
    22
    32
    44
    55
    012345
    groups
    4
    size[0]
    2
    size[2]
    2

    3Connect 2 and 3. Another tie, so 3 becomes a child of 2.

  4. parent
    00
    10
    22
    32
    44
    54
    012345
    groups
    3
    size[0]
    2
    size[2]
    2
    size[4]
    2

    4Connect 4 and 5. Another tie, so 5 becomes a child of 4. There are now three groups of two.

  5. parent
    00
    10
    22
    32
    44
    54
    012345
    ra
    0
    rb
    2

    5Connect 1 and 3. Their roots are 0 and 2, which differ, so the two groups will be merged.

  6. parent
    00
    10
    20
    32
    44
    54
    012345
    groups
    2
    size[0]
    4
    size[4]
    2

    6Both roots have size 2, which is a tie, so root 2 becomes a child of root 0. Changing one pointer merged two groups, and four computers are now in one group. Computer 3 is two hops from its root.

  7. parent
    00
    10
    20
    30
    44
    54
    012345
    groups
    2
    size[0]
    4
    size[4]
    2

    7find(3) walks 3 → 2 → 0 and, on the way back, points 3 directly at the root. This is path compression, and the next find(3) takes one hop.

  8. parent
    00
    10
    20
    30
    44
    54
    012345
    ra
    0
    rb
    4

    8Connect 5 and 3. find(5) is 4 with size 2 and find(3) is 0 with size 4. The group of 4 is smaller, so the swap makes ra = 0 and rb = 4, and root 4 will go under root 0.

  9. parent
    00
    10
    20
    30
    40
    54
    012345
    groups
    1
    size[0]
    6

    9Root 4 now points to 0. Only computers 4 and 5 ended up one hop further from their root, whereas putting 0 under 4 would have moved the four computers 0, 1, 2 and 3 one hop further.

  10. parent
    00
    10
    20
    30
    40
    50
    012345
    groups
    1
    union(5, 1)
    false

    10Connect 5 and 1. find(5) walks 5 → 4 → 0 and points 5 at 0. find(1) is also 0, so union returns false because the two computers were already connected.

  11. parent
    00
    10
    20
    30
    40
    50
    012345
    groups
    1
    longest find
    1 hop

    11All six computers are in one group and each points directly at root 0, so any find now takes one hop.

1 / 11

Keeping the trees shallow

The cost of every operation is the length of the walk inside find, so the trees have to stay shallow. If union always puts the first root under the second, the connections 0–1, 1–2, 2–3 and 3–4 build a chain, and find(0) takes as many steps as there are items. That is no better than searching the graph. Two techniques prevent this, and real implementations use both.

Naive union 4 3 2 1 0 4 hops Union by size 0 1 2 3 4 every find: 1 hop
The same five computers after the connections 0–1, 1–2, 2–3 and 3–4. On the left, always putting the first root under the second builds a chain, and find(0) takes 4 hops. On the right, union by size keeps every computer 1 hop from the root.

Union by size

When merging, make the root of the smaller group a child of the root of the larger group. An item only gets deeper when its group is attached under a group at least as big, so that item's group at least doubles in size every time its depth grows. A group can double only about log₂ n times, so no item is ever deeper than log₂ n, which is about 20 for a million items. A common alternative is union by rank, which compares tree heights instead of sizes and gives the same bound. Size is easier to keep correct, and it is also useful when a problem asks for the size of a group.

Path compression

While find walks up to the root, it makes every item on the path point directly at the root. The walk was happening anyway, so this costs almost nothing, and any later find from those items takes one hop. The trace shows this when find(3) shortens the path from 3.

Used together, the two techniques give an amortized cost of O(α(n)) per operation, where α is the inverse Ackermann function. It is at most 4 for any n that fits in memory, so you can treat it as constant.

Code

class UnionFind {
  constructor(n) {
    this.parent = Array.from({ length: n }, (_, i) => i); // everyone is their own root
    this.size = new Array(n).fill(1);
    this.groups = n;
  }
 
  find(x) {
    if (this.parent[x] !== x) {
      this.parent[x] = this.find(this.parent[x]); // path compression
    }
    return this.parent[x];
  }
 
  union(a, b) {
    let rootA = this.find(a);
    let rootB = this.find(b);
    if (rootA === rootB) return false; // already in the same group
    if (this.size[rootA] < this.size[rootB]) [rootA, rootB] = [rootB, rootA];
    this.parent[rootB] = rootA; // smaller tree goes under the bigger one
    this.size[rootA] += this.size[rootB];
    this.groups--;
    return true;
  }
}
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))  # everyone is their own root
        self.size = [1] * n
        self.groups = n
 
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])  # path compression
        return self.parent[x]
 
    def union(self, a, b):
        root_a, root_b = self.find(a), self.find(b)
        if root_a == root_b:
            return False  # already in the same group
        if self.size[root_a] < self.size[root_b]:
            root_a, root_b = root_b, root_a
        self.parent[root_b] = root_a  # smaller tree goes under the bigger one
        self.size[root_a] += self.size[root_b]
        self.groups -= 1
        return True

To test whether a and b are connected, compare find(a) with find(b). The groups counter is the number of separate groups, and it goes down only when a union really merges two groups. When union returns false, the two items were already connected.

Two details are easy to get wrong. A connection test must compare find(a) with find(b), not parent[a] with parent[b]: after the connection 1–3 in the trace, parent[1] is 0 and parent[3] is 2, yet the two computers are in the same group. For the same reason, call find(x) instead of reading parent[x] when you list the members of each group at the end, because after a union only the root of the smaller group has changed its parent.

ApproachTimeSpaceWhy
Re-run BFS or DFS per questionO(V + E) per questionO(V)Walks the whole graph every time.
Union-find, no tricksO(n) per operationO(n)Trees can turn into chains.
Union by size onlyO(log n) per operationO(n)An item gets deeper only when its group at least doubles, so depth stays under log₂ n.
Union by size and path compressionO(α(n)) amortizedO(n)α(n) is at most 4 for any realistic n, so this is effectively constant.

"Amortized" means averaged over a sequence of operations. A single find can walk several hops, but it flattens the path it walked, so the later finds on those items are cheap.

Variants and limits

Items that are not small integers

The array version needs items numbered 0 to n - 1. When the items are strings, coordinates or other objects, keep parent and size in hash maps instead, and create an entry for an item the first time you see it. For a grid, a common trick is to turn cell (r, c) into the number r * cols + c and use the array version.

Iterative find

The recursive find is short, but with union by size its depth is at most about log₂ n, so the recursion is safe. If you leave out union by size, a chain of 100,000 items overflows the recursion limit in Python. When you want to avoid recursion, loop while parent[x] != x, set parent[x] = parent[parent[x]], and move x to its parent. This is called path halving. It keeps the same complexity as full path compression.

Tracking extra information per group

Because every group has a root, the root can hold anything that can be combined when two groups merge: the size, the smallest member, the total of a value, or a count of edges. Update it in union on the new root, exactly as size is updated in the code above. Problems that ask for the largest group or for a group's total are solved this way.

When union-find does not apply

Union-find cannot split a group. If connections are removed as well as added, it cannot undo a union, so the data structure does not fit. When all the changes are known in advance, you can sometimes process them in reverse order, so that removals become additions. Otherwise use a graph search after each change, or a more advanced structure. It also does not return paths. If a problem needs the route between two items, or the shortest distance, use BFS, DFS or Dijkstra's algorithm. Finally, for a graph that never changes, one DFS that labels each component is simpler and just as fast.

In the interview

Consider union-find when the problem is about items being merged into groups and you must repeatedly ask whether two items are connected, or how many groups remain. Interviewers usually expect you to write the class from memory, with both optimizations, and then to explain the complexity and why find must return the root. Typical statements are "given a list of edges, count the connected components", "are these two accounts the same person, given pairs that share an email", "find the edge that creates a cycle", and "process connections as they arrive and report the component count after each". A graph problem that asks only for one final answer can also use union-find. The same code works for building a minimum spanning tree with Kruskal's algorithm, where it decides whether a cheap edge would close a cycle (see Minimum Spanning Trees).

Questions to expect:

  • "Why not just run BFS each time?" A search costs O(V + E) per query. Union-find handles a stream of connections and queries in nearly constant time each, because it stores only the group of each item and never needs the paths.
  • "What is the complexity?" With union by size and path compression, each operation is O(α(n)) amortized, which is effectively constant. Without path compression, union by size alone gives O(log n). The space is O(n) for the two arrays.
  • "Why do you need union by size if you already compress paths?" Path compression alone still gives O(log n) amortized, but a single find can be slow right after a chain has formed. Union by size prevents the long chains from forming, and the two together give the near-constant bound. Interviewers usually accept either one, as long as you can explain what it does.
  • "How would you detect a cycle in an undirected graph?" Call union(u, v) for each edge. If it returns false, u and v were already connected, so that edge closes a cycle. This works for undirected graphs only. For a directed graph, use DFS with a visiting state or a topological sort.
  • "How do you handle deletions?" Union-find cannot undo a union. If the deletions are known up front, process the operations in reverse so each deletion becomes a union. Otherwise rebuild the structure or use a different technique.
  • "What are union by rank and path halving?" Union by rank compares the heights of the two trees instead of their sizes and gives the same depth bound. Path halving is an iterative form of path compression that points each visited item at its grandparent. Either is an acceptable substitute in an interview if you can say why it keeps the trees shallow.
  • "Union-find or DFS for counting components?" For a fixed graph, both take about O(V + E), and DFS is simpler. Union-find is the better choice when edges arrive one at a time and you need the answer after each one.
Quick check

parent = [0, 0, 1, 3, 3]. Which computers are in the same group as 2?

Root A has a group of 10 and root B has a group of 3. With union by size, what does union do?

You call union(u, v) on each edge of an undirected graph in turn, and one call returns false. What does that tell you?

What to practise next

Try the problems One Cable Too Many and Wiring the Campsites. Then read Minimum Spanning Trees, where union-find decides which edges to keep, or Dijkstra's Algorithm for shortest paths in weighted graphs.