synopsis · Trees & graphs · chapter 28
Union-Find & Minimum Spanning Trees
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
Union-Find:
parent[]forest, root = group name.findwalks up;unionlinks two roots. MST: the cheapest set of n − 1 edges connecting everything. - use it when
Pairs or edges arrive and you ask "same group?", count groups, spot the edge that closes a cycle — or "connect all at minimum cost".
- template
find:if (parent[x] != x) parent[x] = find(parent[x]);·union: roots equal → false; else smaller size under bigger,count--. - cost
Both tricks: O(α(n)) amortized per op — effectively constant. Kruskal O(E log E). Lazy Prim O(E log E). Dense Prim O(V²).
- trap
parent[a] == parent[b]is not "same set" — comparefind(a) == find(b). And link roots:parent[find(a)] = find(b). - trap
DSU ignores direction: never use it for directed cycles (use DFS colours or Kahn's). It also can't split a group.
- pro tip
Valid tree = exactly n − 1 edges + no union fails. Make network connected = components − 1, if cables ≥ n − 1.
- pro tip
Every pair of points is an edge? Use dense Prim with a
best[]array — no 5-lakh-edge list to build and sort. - trap
Kruskal that ends with fewer than n − 1 edges means disconnected — there is no spanning tree. Check it.
Shaky on a card? Open the chapter or flip its recall cards.