Skip to main content
Advanced ~14 min read

Minimum Spanning Trees (Prim's & Kruskal's)

Connect every node with the least total wire: the cut property, Kruskal's sort-everything strategy, and Prim's grow-one-node strategy.

Prerequisites: Graph Representations, Greedy Algorithms

A spanning tree of a connected, undirected graph is a subset of edges that keeps every node reachable with no cycles, exactly V − 1 edges for V nodes. Weighted graphs usually have many spanning trees, and the minimum spanning tree (MST) is the one with the smallest total weight. The canonical applications are physical networks: laying cable, pipes, roads, or cluster analysis, any problem where you must connect everything while spending as little as possible.

Both classical algorithms are greedy, and both are provably correct because of one fact, the cut property: take any partition of the nodes into two groups; the lightest edge crossing that cut is safe, some MST contains it. Why? If an MST lacked it, adding the edge would create a cycle crossing the cut at least twice; drop the other crossing edge and you get a lighter spanning tree, contradiction. Kruskal and Prim differ only in which cuts they exploit.

Kruskal's algorithm

  1. 1

    Sort all edges by weight

    Ascending. This is the dominant cost: O(E log E).

  2. 2

    Sweep and union

    For each edge (u, v): if u and v are in different components (union-find says find(u) ≠ find(v)), take the edge and union the components. Otherwise skip, it would close a cycle.

  3. 3

    Stop at V − 1 edges

    The spanning tree is complete. Union-find with path compression + union by rank makes each operation nearly O(1) amortized, so total cost is O(E log E), dominated by the sort.

Prim's algorithm

  1. 1

    Grow from any start node

    Maintain a frontier priority queue of edges leaving the current tree. Pop the lightest edge whose far end is outside the tree; add both edge and node.

  2. 2

    Push new crossing edges

    Each added node pushes its outgoing edges into the PQ. Stale edges (both ends already inside) are skipped on pop.

  3. 3

    Complexity

    O(E log V) with a binary heap. Structurally, Prim is Dijkstra with the distance replaced by the single edge weight, growth by cheapest edge instead of growth by cheapest total path.

Kruskal with union-find

kruskal.js
function kruskal(n, edges) {               // edges: [weight, u, v][]
  edges.sort((a, b) => a[0] - b[0]);       // O(E log E)
  const parent = Array.from({ length: n }, (_, i) => i);
  const find = (x) => (parent[x] === x ? x : (parent[x] = find(parent[x])));

  const mst = [];
  for (const [w, u, v] of edges) {
    const ru = find(u), rv = find(v);
    if (ru === rv) continue;               // same component → would cycle
    parent[ru] = rv;                       // union
    mst.push([u, v, w]);
    if (mst.length === n - 1) break;       // spanning tree complete
  }
  return mst;                              // V−1 edges, minimum total weight
}

Cost summary

Operation / caseCostNotes
KruskalO(E log E)sort + near-O(1) unions; best on sparse graphs
Prim with binary heapO(E log V)best on dense graphs
MST edge countV − 1always, a tree by definition

The MST is unique when all edge weights are distinct, a nice consequence of the cut property worth saying in interviews.

Practice

A connected graph has 10 nodes. How many edges does its MST contain?

Reveal explanation

Every spanning tree on V nodes has exactly V − 1 edges, enough for connectivity, one short of creating a cycle.

Check your understanding

  1. 1.Which fact makes both greedy MST algorithms correct?
  2. 2.In Kruskal, why skip an edge whose endpoints share a component?
  3. 3.Dense graph (E ≈ V²), weights fine, memory OK. Better MST choice?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going