TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › Disjoint-Set Operations and Connected Components

Disjoint-Set Operations and Connected Components

Some problems need to keep track of a partition: a collection of elements split into groups, where groups only ever merge. Which computers are connected after these cables were plugged in? Which pixels belong to the same region? Which vertices has Kruskal's algorithm already joined into one tree? Which variables were declared equal by a type checker? A disjoint-set structure (also called union-find) answers exactly these questions, and its best implementation is so fast that the cost per operation is a constant for every input that fits in the universe.

This lesson fixes the interface and solves the connected-components problem with it. The next three lessons build the structure: first with linked lists, then with the forests that make it almost linear, and finally the analysis.

The operations

A disjoint-set structure maintains a collection S={S1,S2,…,Sk}\mathcal{S} = \{S_1, S_2, \ldots, S_k\} of pairwise disjoint sets. Each set is identified by a representative, one of its members. It does not matter which member, but asking twice without changing the set in between must give the same answer.

Operation Meaning
MAKE-SET(x)(x) create the set {x}\{x\}; xx must not be in any set yet, and becomes its representative
UNION(x,y)(x, y) replace the sets containing xx and yy by their union (nothing happens if they are the same set)
FIND-SET(x)(x) return the representative of the set containing xx

Two elements are in the same set exactly when FIND-SET returns the same representative for both. The analysis uses two parameters: nn, the number of MAKE-SET operations (the number of elements), and mm, the total number of operations, MAKE-SETs included. Each UNION reduces the number of sets by one, so there are at most n−1n - 1 effective unions.

A first implementation: relabelling

The simplest representation stores, for each element, the name of its set's representative in an array label. FIND-SET is a single lookup. UNION must relabel every element of one of the two sets, which takes Θ(n)\Theta(n) if it scans the array.

python · try it yourself
class Relabel:
    def __init__(self, n):
        self.label = list(range(n))          # MAKE-SET for 0..n-1
        self.work = 0                          # array cells examined by unions
    def find(self, x):
        return self.label[x]
    def union(self, x, y):
        a, b = self.label[x], self.label[y]
        if a == b:
            return
        for v in range(len(self.label)):       # relabel set b as set a
            self.work += 1
            if self.label[v] == b:
                self.label[v] = a

ds = Relabel(8)
for x, y in [(0, 1), (2, 3), (1, 3), (5, 6)]:
    ds.union(x, y)
    print(f"union({x}, {y}): labels {ds.label}")
print("same set? 0 and 2:", ds.find(0) == ds.find(2), "| 0 and 5:", ds.find(0) == ds.find(5))
print("sets:", len(set(ds.label)), "| array cells examined:", ds.work)
union(0, 1): labels [0, 0, 2, 3, 4, 5, 6, 7]
union(2, 3): labels [0, 0, 2, 2, 4, 5, 6, 7]
union(1, 3): labels [0, 0, 0, 0, 4, 5, 6, 7]
union(5, 6): labels [0, 0, 0, 0, 4, 5, 5, 7]
same set? 0 and 2: True | 0 and 5: False
sets: 4 | array cells examined: 32

With nn elements and n−1n - 1 unions this costs Θ(n2)\Theta(n^2). The linked-list representation relabels only the members of one set, and with one simple rule brings the total down to O(nlg⁡n)O(n \lg n); forests do much better still.

Connected components

An undirected graph G=(V,E)G = (V, E) splits into connected components: maximal groups of vertices joined by paths. With a disjoint-set structure, they are found by one MAKE-SET per vertex and one UNION per edge. Afterwards, two vertices are in the same component exactly when they have the same representative.

text
CONNECTED-COMPONENTS(G)
1  for each vertex v in G.V
2      MAKE-SET(v)
3  for each edge (u, v) in G.E
4      if FIND-SET(u) != FIND-SET(v)
5          UNION(u, v)

SAME-COMPONENT(u, v)
1  return FIND-SET(u) == FIND-SET(v)

Correctness. By induction over the edges processed: after processing a set of edges E′E', the sets are exactly the connected components of (V,E′)(V, E'). Initially E′E' is empty and every vertex is its own component. Adding an edge (u,v)(u, v) either joins two components of (V,E′)(V, E') into one, which is what UNION does, or connects two vertices already in the same component, which changes nothing.

Breadth-first or depth-first search finds the components too, in O(V+E)O(V + E) time. The disjoint-set approach wins when the edges arrive over time and questions are asked in between: a search would have to start over after every new edge, while union-find just processes the new edge. This is the practice problem Components After Each Union, which asks for the number of components after each new link.

The program uses a forest implementation (explained two lessons later; here it is only a tool) to process a stream of links between 10 computers and reports the number of components after each one.

python · try it yourself
parent = list(range(10))                  # MAKE-SET for computers 0..9

def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]     # path halving, a form of compression
        x = parent[x]
    return x

def union(x, y):
    rx, ry = find(x), find(y)
    if rx == ry:
        return False
    parent[ry] = rx
    return True

components = 10
links = [(0, 1), (2, 3), (1, 3), (4, 5), (0, 2), (6, 7), (8, 9), (5, 6), (4, 7), (9, 0)]
for u, v in links:
    merged = union(u, v)
    components -= merged
    print(f"link {u}-{v}: {'merged two components' if merged else 'already connected'}, {components} component(s)")
groups = {}
for v in range(10):
    groups.setdefault(find(v), []).append(v)
print("components:", sorted(groups.values()))
link 0-1: merged two components, 9 component(s)
link 2-3: merged two components, 8 component(s)
link 1-3: merged two components, 7 component(s)
link 4-5: merged two components, 6 component(s)
link 0-2: already connected, 6 component(s)
link 6-7: merged two components, 5 component(s)
link 8-9: merged two components, 4 component(s)
link 5-6: merged two components, 3 component(s)
link 4-7: already connected, 3 component(s)
link 9-0: merged two components, 2 component(s)
components: [[0, 1, 2, 3, 8, 9], [4, 5, 6, 7]]

The link 11-33 was a real merge, but 00-22 came after 00 and 22 had already been connected through 11 and 33, and 44-77 after the path 44-55-66-77 existed: those two links close cycles. Recording which links close cycles is exactly how Kruskal's algorithm avoids them when it builds a minimum spanning tree.

In C++

The same idea on a grid: every land cell # is an element, and neighbouring land cells are united. Counting the effective unions gives the number of islands, since each one merges two of them. The disjoint-set structure is the forest of the next lessons, in a few lines.

cpp · try it yourself
#include <cstdio>
#include <numeric>
#include <string>
#include <vector>

struct DSU {
    std::vector<int> p;
    explicit DSU(int n) : p(n) { std::iota(p.begin(), p.end(), 0); }    // MAKE-SET for 0..n-1
    int find(int x) { while (p[x] != x) x = p[x] = p[p[x]]; return x; }   // with path halving
    bool unite(int a, int b) { a = find(a); b = find(b); if (a == b) return false; p[b] = a; return true; }
};

int main() {
    std::vector<std::string> grid = {
        "##..#....#",
        "#...##...#",
        "..#......#",
        "..##..##..",
        "#.....##.#",
    };
    int rows = static_cast<int>(grid.size()), cols = static_cast<int>(grid[0].size());
    DSU ds(rows * cols);
    int land = 0, merges = 0;
    for (int r = 0; r < rows; ++r)
        for (int c = 0; c < cols; ++c) {
            if (grid[r][c] != '#') continue;
            ++land;
            if (r > 0 && grid[r - 1][c] == '#') merges += ds.unite(r * cols + c, (r - 1) * cols + c);
            if (c > 0 && grid[r][c - 1] == '#') merges += ds.unite(r * cols + c, r * cols + c - 1);
        }
    std::printf("%d land cells, %d merges, %d islands\n", land, merges, land - merges);
    bool same = ds.find(0 * cols + 4) == ds.find(1 * cols + 5);
    std::printf("cells (0,4) and (1,5) on the same island: %s\n", same ? "yes" : "no");
}
18 land cells, 11 merges, 7 islands
cells (0,4) and (1,5) on the same island: yes

Other uses

  • Kruskal's minimum spanning tree: sort the edges by weight and add an edge whenever its endpoints are in different sets. The union-find work is almost linear, so sorting dominates.
  • Image segmentation and percolation: pixels or grid cells are elements, and neighbouring cells of the same kind are united. Counting islands in a grid (Number of Islands) works this way as well as with a search.
  • Equivalence of names: compilers unify type variables, and the "offline" form of many problems (least common ancestors, for example) is solved by processing queries in a clever order with union-find.

Test yourself

After MAKE-SET for a,b,c,da, b, c, d and then UNION(a,b)(a, b) and UNION(c,d)(c, d), how many sets are there?

  1. 1
  2. 2
  3. 3
  4. 4

How do you test whether xx and yy are in the same set?

  1. UNION(x,y)(x, y) and check the size
  2. compare FIND-SET(x)(x) with FIND-SET(y)(y)
  3. check whether x=yx = y
  4. scan all sets

Why use union-find rather than breadth-first search for connected components when edges arrive one at a time?

  1. BFS cannot find components
  2. union-find processes each new edge in nearly constant time, while BFS would have to be rerun after each edge
  3. union-find uses less memory than an adjacency list
  4. BFS only works on trees