Courses / DSA Patterns for Working Engineers / Chapter 26
Module 8 · Hash maps, tracking, union-find and custom structures · Chapter 26 of 39
Union-Find: Merging Groups and Finding Redundant Links
Builds on Graphs: Modelling, Breadth-First and Depth-First Search. Next up: Custom Data Structures: Composing Maps, Lists and Arrays.
Part 1 · Introduction to union-find
Groups that only merge
A telecom company joins villages with cables, a social app merges duplicate profiles and a map tool counts islands, and in each case groups only ever merge.
Each keeps items in groups and merges two groups when a link appears.
A disjoint-set union, also called union-find or DSU, keeps a set of items split into groups that do not overlap, and answers two questions fast. find(x) returns the representative of x's group, a label that is the same for every member. union(a, b) merges the groups of a and b. Two items are in the same group exactly when their find results are equal, so find(a) === find(b) answers "are these connected?".
The structure fits any question of the form "are these linked, directly or through others?" when links only get added. A breadth-first search can answer one such question in O(n + m) time, but it has to run again after every new link. Union-find handles a stream of links and queries, with each step costing close to a constant.
A useful by-product is the group count: it starts at n and each union that really merges two groups reduces it by one.