Union Find

Track which items belong to the same group as edges arrive. With path compression and union by rank, find and union cost almost O(1) each.

Overview

What it is

Union Find, also called a disjoint set union (DSU), keeps a collection of groups that never overlap. It answers two questions fast: which group is x in (find), and merge the groups of x and y (union). It does not store the edges of a graph, only the groups they create, so it is the tool for questions about connectivity that do not need paths.

Each group is a tree. Every item points to a parent, and the root of the tree, which points to itself, is the group's name. Two items are in the same group when find reaches the same root for both. The whole structure is one array, parent, where parent[i] = i marks a root.

Read the picture through the array. Items 1 and 2 point at 0, 3 points at 2, and 5 points at 4, while 0 and 4 point at themselves. So find(3) climbs from 3 to 2 to 0, and find(5) climbs from 5 to 4. The roots differ, so 3 and 5 are in different groups. The next section builds exactly this picture from six single items, and then merges the two groups.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio