Minimum spanning tree

Connect every vertex of a weighted graph using the cheapest possible set of edges, with no cycles: Kruskal's and Prim's greedy algorithms.

Description

Suppose you need to connect six offices with network cables, and each possible link has a cost. You want every office reachable from every other, at the lowest total cost. Any solution with a cycle has a redundant link, so the answer is a tree that spans every vertex: a minimum spanning tree.

Kruskal's algorithm sorts all edges by weight and adds them cheapest first, skipping any edge that would create a cycle. Union-find tells you in near-constant time whether an edge's two ends are already connected. After V − 1 edges, the tree is complete.

Prim's algorithm grows the tree from a single vertex instead, always adding the cheapest edge that connects the tree to a new vertex, using a priority queue, much like Dijkstra's algorithm.

Both are greedy: they make the locally best choice at each step and never reconsider, and for this problem that's provably optimal. MSTs are used in network design, clustering (remove the most expensive MST edges to split groups), and as approximations for harder problems such as the traveling salesperson.

How it works

42581023ABCDEF

All possible links and their costs

  1. A — B (weight 4)
  2. A — C (weight 2)
  3. B — D (weight 5)
  4. C — D (weight 8)
  5. C — E (weight 10)
  6. D — F (weight 2)
  7. E — F (weight 3)
All possible links and their costs
22345ABCDEF

The minimum spanning tree: five links, total cost 16

  1. A — C (weight 2)
  2. D — F (weight 2)
  3. E — F (weight 3)
  4. A — B (weight 4)
  5. B — D (weight 5)
The minimum spanning tree: five links, total cost 16

Complexity

OperationAverageWorst
Kruskal's (sort + union-find)Dominated by sorting the edges.O(E log E)O(E log E)
Prim's with a binary heapO(E log V)O(E log V)
Prim's with an adjacency matrixGood for dense graphs.O(V²)O(V²)

Space: O(V + E)

TypeScript implementation

Kruskal's algorithm using union-find to skip edges that would form a cycle.

minimum-spanning-tree.ts
// Kruskal's algorithm: add edges cheapest first, skipping any that would
// close a cycle. A small union-find tracks which vertices are connected.

type Edge = { a: string; b: string; weight: number };

export function kruskal(vertices: string[], edges: Edge[]): { tree: Edge[]; total: number } {
  const parent = new Map(vertices.map((v) => [v, v]));
  const find = (v: string): string => {
    while (parent.get(v) !== v) {
      parent.set(v, parent.get(parent.get(v)!)!); // path halving
      v = parent.get(v)!;
    }
    return v;
  };
  const tree: Edge[] = [];
  for (const e of [...edges].sort((x, y) => x.weight - y.weight)) {
    const ra = find(e.a), rb = find(e.b);
    if (ra === rb) continue; // would create a cycle
    parent.set(ra, rb);
    tree.push(e);
    if (tree.length === vertices.length - 1) break;
  }
  return { tree, total: tree.reduce((s, e) => s + e.weight, 0) };
}

export function demo(): string[] {
  const links: Edge[] = [
    { a: "A", b: "B", weight: 4 }, { a: "A", b: "C", weight: 2 }, { a: "B", b: "D", weight: 5 }, { a: "C", b: "D", weight: 8 },
    { a: "C", b: "E", weight: 10 }, { a: "D", b: "F", weight: 2 }, { a: "E", b: "F", weight: 3 },
  ];
  const { tree, total } = kruskal(["A", "B", "C", "D", "E", "F"], links);
  return [
    `cables to lay: ${tree.map((e) => `${e.a}–${e.b} (${e.weight})`).join(", ")}`,
    `total cost ${total}, instead of ${links.reduce((s, e) => s + e.weight, 0)} for every link`,
  ];
}

When to use it

Use it when

  • Connecting everything at minimum total cost: networks, pipelines, roads, wiring.
  • Clustering: build the MST and cut its most expensive edges.
  • Approximating harder optimization problems.

Avoid it when

  • You need the shortest path between two points: an MST minimizes the total, not individual paths. Use Dijkstra.
  • The graph is directed: you need a minimum arborescence algorithm instead.
  • You need redundancy: an MST has exactly one path between any two vertices, so one failure disconnects it.

Pitfalls

  • Confusing MST with shortest paths: the path between two vertices in an MST can be much longer than their shortest path.
  • Disconnected graphs, which have a spanning forest rather than a tree. Check the edge count at the end.
  • Cycle checks without union-find, which make Kruskal's slow.

Alternatives

Dijkstra's shortest path

Choose it when you need cheapest paths from one source, not cheapest total connection.

Steiner tree

Choose it when only some vertices must be connected (a much harder problem).