Kruskal's MST
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Kruskal's method connects everything with the cheapest possible total cost by taking the cheapest links first and skipping any link that joins two already connected places. Union-find is what makes that "already connected?" check fast.
Practical use cases
- Web app: Cheapest cabling plan tool. A telecom planning web app has 5 villages and a list of possible fibre routes with prices. The planner clicks "suggest cheapest layout". The app sorts routes by price, takes each if it joins two separate groups, and ends with every village connected at the lowest total price.
- Web app: Delivery hub network designer. A logistics dashboard must link 200 warehouses with the least total road cost. Instead of trying every combination, it adds the cheapest road that connects new areas, and skips roads that would be redundant. The plan comes out of a single sorted pass, and the total cost is the lowest possible for connecting all sites.
- System: Clustering and pipe layouts. Data analysts group similar points by stopping Kruskal early, and city engineers use it to lay water pipes with the least pipe length. Because each link is judged with a quick connected check, even a map with a million possible links stays manageable.
The story: Water Pipes for Five Villages
A district engineer had a budget problem. Five villages needed water from a common tank, and the pipes between them had very different costs because of rocks, rivers and roads. "Connect every village, but spend as little as possible," said the collector. Mira, visiting her uncle the engineer, was curious how he would pick.
Her uncle laid all possible pipes in a list and sorted them from cheapest to costliest. "I will take the cheapest first. But I must not waste pipes. If two villages are already linked by other pipes, this one is useless; skip it."
"How do you know they are already linked?" Mira asked. He grinned and drew a small table: one entry per village, pointing at a group leader. For each pipe, he looked up the leaders of both ends. Same leader? Skip. Different leader? Buy the pipe and merge the two groups. That table was Union-Find.
When he had bought four pipes (one fewer than the villages), everyone was connected and he stopped. The result is a minimum spanning tree, and the method is called Kruskal's algorithm. It is a greedy plan (always take the cheapest safe option) powered by the union-find cycle check.
How to spot this problem, and where you need it
You must connect all places with links so that everything is reachable, while keeping the total cost as low as possible.
Signs you need it
- The problem says "minimum spanning tree", "cheapest way to connect everything" or "least total cable/pipe/road".
- You have a list of possible links with a cost for each, and every place must end up connected.
- Trying all combinations of links is impossible because the number of combinations explodes.
- Redundant links (that add a loop) should be avoided.
Where to use it in a project
- Network, cabling and utility layout planning tools for engineers.
- Grouping or clustering features where the weakest links decide how groups split.
The solution
Sort all links from cheapest to dearest. Start with every place as its own group. Go through the links in that order; for each, find the groups of its two ends with union-find. If they are different, take the link and merge the groups; if they are the same, skip it since it would form a loop. Stop when everything is in one group.
Payoff: Before: trying millions of link combinations. After: one sort and one pass, finishing in a blink.
Explain it like I am 8
You have a pile of ropes of different prices and want to join all treehouses. Buy the cheapest rope first, then the next cheapest, but if a rope would only join two treehouses that are already joined, leave it on the shelf.
How it works, step by step
- List every edge with its cost and sort them cheapest first.
- Make a set for every village (union-find).
- Take the next edge. If
find(a) != find(b), the edge is safe: keep it,unionthem, add its cost. - Otherwise skip it because it would form a cycle.
- Stop when you have kept
n - 1edges (or run out of edges, which means the graph was not fully connected).
The code in four languages
PHP
<?php
class DSU {
private array $parent = [];
private array $size = [];
public function __construct(int $n) {
for ($i = 0; $i < $n; $i++) { $this->parent[$i] = $i; $this->size[$i] = 1; }
}
public function find(int $x): int {
while ($this->parent[$x] !== $x) {
$this->parent[$x] = $this->parent[$this->parent[$x]];
$x = $this->parent[$x];
}
return $x;
}
public function union(int $a, int $b): bool {
$ra = $this->find($a);
$rb = $this->find($b);
if ($ra === $rb) return false;
if ($this->size[$ra] < $this->size[$rb]) [$ra, $rb] = [$rb, $ra];
$this->parent[$rb] = $ra;
$this->size[$ra] += $this->size[$rb];
return true;
}
}
function kruskal(int $n, array $edges): array {
usort($edges, fn($x, $y) => $x[2] <=> $y[2]); // cheapest first
$dsu = new DSU($n);
$names = "ABCDE";
$chosen = [];
$total = 0;
foreach ($edges as [$a, $b, $cost]) {
if ($dsu->union($a, $b)) { // different groups: safe to buy
$chosen[] = $names[$a] . "-" . $names[$b];
$total += $cost;
if (count($chosen) === $n - 1) break; // enough pipes, stop
}
}
return [$chosen, $total];
}
$pipes = [[0, 1, 4], [0, 2, 2], [1, 2, 5], [1, 3, 3], [2, 3, 7], [2, 4, 8], [3, 4, 6]];
[$chosen, $total] = kruskal(5, $pipes);
echo implode(", ", $chosen) . " | total cost " . $total . "\n"; // A-C, B-D, A-B, D-E | 15JavaScript
class DSU {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.size = Array(n).fill(1);
}
find(x) {
while (this.parent[x] !== x) {
this.parent[x] = this.parent[this.parent[x]];
x = this.parent[x];
}
return x;
}
union(a, b) {
let ra = this.find(a);
let rb = this.find(b);
if (ra === rb) return false;
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra];
this.parent[rb] = ra;
this.size[ra] += this.size[rb];
return true;
}
}
function kruskal(n, edges) {
const sorted = [...edges].sort((x, y) => x[2] - y[2]); // cheapest first
const dsu = new DSU(n);
const names = "ABCDE";
const chosen = [];
let total = 0;
for (const [a, b, cost] of sorted) {
if (dsu.union(a, b)) { // different groups: safe to buy
chosen.push(names[a] + "-" + names[b]);
total += cost;
if (chosen.length === n - 1) break; // enough pipes, stop
}
}
return [chosen, total];
}
const pipes = [[0, 1, 4], [0, 2, 2], [1, 2, 5], [1, 3, 3], [2, 3, 7], [2, 4, 8], [3, 4, 6]];
const [chosen, total] = kruskal(5, pipes);
console.log(chosen.join(", ") + " | total cost " + total); // A-C, B-D, A-B, D-E | 15Java
import java.util.*;
public class Main {
static class DSU {
private final int[] parent;
private final int[] size;
DSU(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }
}
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
boolean union(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) return false;
if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; }
parent[rb] = ra;
size[ra] += size[rb];
return true;
}
}
public static void main(String[] args) {
int[][] pipes = {{0, 1, 4}, {0, 2, 2}, {1, 2, 5}, {1, 3, 3}, {2, 3, 7}, {2, 4, 8}, {3, 4, 6}};
int n = 5;
int[][] sorted = pipes.clone();
Arrays.sort(sorted, (x, y) -> Integer.compare(x[2], y[2])); // cheapest first
DSU dsu = new DSU(n);
String names = "ABCDE";
List<String> chosen = new ArrayList<>();
int total = 0;
for (int[] e : sorted) {
int a = e[0], b = e[1], cost = e[2];
if (dsu.union(a, b)) { // different groups: safe to buy
chosen.add(names.charAt(a) + "-" + names.charAt(b));
total += cost;
if (chosen.size() == n - 1) break; // enough pipes, stop
}
}
System.out.println(String.join(", ", chosen) + " | total cost " + total); // A-C, B-D, A-B, D-E | 15
}
}Go
package main
import (
"fmt"
"sort"
"strings"
)
type DSU struct {
parent []int
size []int
}
func NewDSU(n int) *DSU {
d := &DSU{parent: make([]int, n), size: make([]int, n)}
for i := range d.parent {
d.parent[i] = i
d.size[i] = 1
}
return d
}
func (d *DSU) Find(x int) int {
for d.parent[x] != x {
d.parent[x] = d.parent[d.parent[x]]
x = d.parent[x]
}
return x
}
func (d *DSU) Union(a, b int) bool {
ra, rb := d.Find(a), d.Find(b)
if ra == rb {
return false
}
if d.size[ra] < d.size[rb] {
ra, rb = rb, ra
}
d.parent[rb] = ra
d.size[ra] += d.size[rb]
return true
}
type pipe struct{ a, b, cost int }
func kruskal(n int, pipes []pipe) ([]string, int) {
sorted := append([]pipe(nil), pipes...)
sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].cost < sorted[j].cost }) // cheapest first
dsu := NewDSU(n)
names := "ABCDE"
var chosen []string
total := 0
for _, p := range sorted {
if dsu.Union(p.a, p.b) { // different groups: safe to buy
chosen = append(chosen, string(names[p.a])+"-"+string(names[p.b]))
total += p.cost
if len(chosen) == n-1 { // enough pipes, stop
break
}
}
}
return chosen, total
}
func main() {
pipes := []pipe{{0, 1, 4}, {0, 2, 2}, {1, 2, 5}, {1, 3, 3}, {2, 3, 7}, {2, 4, 8}, {3, 4, 6}}
chosen, total := kruskal(5, pipes)
fmt.Println(strings.Join(chosen, ", ") + " | total cost " + fmt.Sprint(total)) // A-C, B-D, A-B, D-E | 15
}Time: O(m log m) · Extra space: O(n). Sorting the m pipes dominates the cost; the union-find checks afterwards are almost free.
Watch out for
- Forgetting to sort first. Without cheapest-first order, the greedy choice is not safe.
- Not checking for a cycle before buying. The same-root test is the whole point of using union-find here.
- Not handling disconnected graphs: if you finish with fewer than n - 1 edges, the villages cannot all be connected (you get a forest, not a tree).
Quick check
- In Kruskal's algorithm, how do you decide to skip an edge?
- It touches village A
- It is the cheapest
- Its two ends already share a root
- Its cost is odd
- How many edges does a minimum spanning tree on 5 villages have?
- 3
- 4
- 10
- 5
- What costs the most time in Kruskal's algorithm?
- Printing
- Sorting the edges
- The union-find steps
- Reading the villages