04
Minimum spanning tree (Kruskal) (Union-Find (DSU) Sub-pattern)
Connect all nodes with the smallest total edge cost.
Signals in the problem statement
- ›
"minimum cost to connect all points / cities"
- ›
"minimum spanning tree"
- ›
"return -1 if it is impossible to connect all"
What makes it different
Kruskal (template) gets the edges directly. Min Cost to Connect All Points has no edge list: every pair of points is an edge (Manhattan distance), so either sort all n² edges for Kruskal or use Prim's O(n²) without a heap. Connecting Cities is Kruskal on 1-indexed cities and returns -1 when fewer than n − 1 edges get used.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Kruskal's Minimum Spanning TreeWalkthroughMediumBasic Anchor·GeeksforGeeks
- 2Min Cost to Connect All PointsWalkthroughMediumBasic Reinforcement·LeetCode #1584
- 3Connecting Cities With Minimum CostWalkthroughMediumSlight Variation·LeetCode #1135 Premium
Template
kruskal-template.cpp
// Kruskal's minimum spanning tree: cheapest edges first, skip any edge inside one group.
// Uses the DSU from the Union-Find template. Returns -1 if the graph is not connected.
long long kruskal(int n, vector<array<int, 3>> edges) { // {weight, u, v}, nodes 0..n-1
sort(edges.begin(), edges.end());
DSU dsu(n);
long long total = 0;
int used = 0;
for (auto& [w, u, v] : edges) {
if (!dsu.unite(u, v)) continue; // would close a cycle: never needed
total += w;
if (++used == n - 1) break; // a spanning tree has exactly n - 1 edges
}
return used == n - 1 ? total : -1;
}Remember this · Union-Find (DSU)
Trigger
Edges arrive one by one, "are these connected?", merge equivalent items, count components, extra edge creating a cycle.
Think
Am I repeatedly merging groups and asking whether two things are in the same group?
Key question
What are the elements, and what does it mean to union two of them?