Graphs · Pattern 13 of 14
Minimum spanning tree: Kruskal's algorithm
Sort the edges by cost and add each one unless it would close a loop (union-find tells you). After n − 1 edges every node is connected as cheaply as possible.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Connect every city, house or point at the lowest total cost
- Any connected result is fine; only the total cost matters
The template
// Kruskal: cheapest edges first, skip any edge that would close a loop. Cities are 1..n.
int minimumCost(int n, int[][] connections) {
int[] parent = new int[n + 1];
for (int i = 0; i <= n; i++) parent[i] = i;
Arrays.sort(connections, (a, b) -> Integer.compare(a[2], b[2]));
int total = 0, used = 0;
for (int[] e : connections) {
int ra = find(parent, e[0]), rb = find(parent, e[1]);
if (ra == rb) continue; // already connected: this edge is a loop
parent[ra] = rb;
total += e[2];
used++;
}
return used == n - 1 ? total : -1; // fewer edges: the graph is not connected
}
int find(int[] parent, int x) {
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }
return x;
} def minimum_cost(n, connections): # Kruskal; cities are 1..n
parent = list(range(n + 1))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
total = used = 0
for a, b, cost in sorted(connections, key=lambda e: e[2]): # cheapest first
ra, rb = find(a), find(b)
if ra != rb: # joins two trees: keep it
parent[ra] = rb
total += cost
used += 1
return total if used == n - 1 else -1 # fewer edges: not connected int findRoot(vector<int>& parent, int x) {
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }
return x;
}
// Kruskal: cheapest edges first, skip any edge that would close a loop. Cities are 1..n.
int minimumCost(int n, vector<vector<int>>& connections) {
vector<int> parent(n + 1);
iota(parent.begin(), parent.end(), 0);
sort(connections.begin(), connections.end(), [](auto& a, auto& b) { return a[2] < b[2]; });
int total = 0, used = 0;
for (auto& e : connections) {
int ra = findRoot(parent, e[0]), rb = findRoot(parent, e[1]);
if (ra == rb) continue; // already connected: this edge is a loop
parent[ra] = rb;
total += e[2];
used++;
}
return used == n - 1 ? total : -1; // fewer edges: the graph is not connected
} // Kruskal: cheapest edges first, skip any edge that would close a loop. Cities are 1..n.
function minimumCost(n, connections) {
const parent = Array.from({ length: n + 1 }, (_, i) => i);
const find = (x) => {
while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; }
return x;
};
let total = 0, used = 0;
for (const [a, b, cost] of [...connections].sort((x, y) => x[2] - y[2])) {
const ra = find(a), rb = find(b);
if (ra === rb) continue; // already connected: this edge is a loop
parent[ra] = rb;
total += cost;
used++;
}
return used === n - 1 ? total : -1; // fewer edges: the graph is not connected
} The variations
-
1Kruskal with union-find
Sort edges by cost and keep each one that joins two different components. With dense graphs (every pair of points), Prim's algorithm with a heap or an O(n²) scan does the same job.
Now you solve
Mistakes to avoid
- Forgetting to check that n − 1 edges were used: if not, some city can never be reached and the answer is −1.
- Using Dijkstra here. Dijkstra minimises the path from one source; an MST minimises the total cost of all edges.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.