1 Minimum Spanning Trees — Kruskal and Prim
A minimum spanning tree (MST) of a connected weighted undirected graph is a spanning tree with minimum total edge weight.
Cut property: for any cut (S, V−S), the minimum-weight edge crossing the cut belongs to some MST. Both algorithms are applications of this property.
Kruskal's algorithm: sort edges by weight O(E log E), then add the next lightest edge if it doesn't create a cycle (Union-Find). Total: O(E log E).
Prim's algorithm: like Dijkstra but keys are edge weights. With a binary heap: O((V + E) log V). With a Fibonacci heap: O(E + V log V).
// Kruskal's MST using Union-Find
function kruskal(n, edges) {
// edges = [[u, v, w], ...], vertices 0..n-1
const parent = Array.from({length: n}, (_, i) => i);
function find(x) { return parent[x] === x ? x : (parent[x] = find(parent[x])); }
function union(a, b) {
const ra = find(a), rb = find(b);
if (ra === rb) return false;
parent[ra] = rb; return true;
}
edges.sort((a, b) => a[2] - b[2]);
const mst = [];
for (const [u, v, w] of edges)
if (union(u, v)) mst.push([u, v, w]);
return mst;
}
// Total MST weight:
const mstEdges = kruskal(4, [[0,1,1],[0,2,4],[1,2,2],[1,3,5],[2,3,3]]);
console.log(mstEdges.reduce((s, e) => s + e[2], 0)); // 6