Minimum Spanning Tree (Kruskal & Prim)

An MST (minimum spanning tree) is a set of edges that joins all V nodes of a graph with no cycle, for the smallest total weight. For a connected graph, an MST…

The power company wants to bring electricity to every village. Cable is expensive, so the total length has to be as short as possible. There's no need for two lines to the same village: as long as every village is connected, that's enough.

The power company's cable network is an example of a minimum spanning tree (MST): a set of edges that joins every node of a graph, with no cycle, for the smallest total weight. In the power company example, the villages are nodes, the cables are edges, and a cable's length is its weight. A cycle is a path that goes back to where it started. A connected graph with no cycle is called a tree.

Kruskal: cheapest first, reject cycles

Kruskal's algorithm sorts every edge from the smallest weight up, then takes them one by one. Nodes already joined to each other by the edges taken are in one group, and at the start each node is its own group. An edge whose two ends are already in one group is rejected, because it would make a cycle. For example, a graph with the edges A-B 4, A-C 2, B-C 1, B-D 5, C-D 8, C-E 10 and D-E 2:

Step Edge (weight) Decision Groups after
1 B-C (1) take {B, C}, {A}, {D}, {E}
2 A-C (2) take {A, B, C}, {D}, {E}
3 D-E (2) take {A, B, C}, {D, E}
4 A-B (4) reject: A and B are already in one group same
5 B-D (5) take {A, B, C, D, E}

The total is 1 + 2 + 2 + 5 = 10, with 4 edges. Every node is in one group now, so C-D and C-E don't need checking. Five nodes, four edges, and that's no accident: the MST of a connected graph (every node can be reached from the others) with V nodes always has exactly V - 1 edges. With fewer, some node isn't joined yet. With more, there is surely a cycle.

Here is the Kruskal code for that graph:

const edges = [
  ["A", "B", 4],
  ["A", "C", 2],
  ["B", "C", 1],
  ["B", "D", 5],
  ["C", "D", 8],
  ["C", "E", 10],
  ["D", "E", 2],
];

function kruskal(nodes, edges) {
  const parent = {};
  for (const n of nodes) {
    parent[n] = n;
  }

  function find(x) {
    while (parent[x] !== x) {
      x = parent[x];
    }
    return x;
  }

  const sorted = [...edges].sort((a, b) => a[2] - b[2]);
  let total = 0;
  let used = 0;

  for (const [a, b, w] of sorted) {
    const ra = find(a);
    const rb = find(b);
    if (ra === rb) continue; // already one group: a cycle

    parent[ra] = rb; // merge the two groups
    total += w;
    used++;
    if (used === nodes.length - 1) break;
  }

  return total;
}

console.log(kruskal(["A", "B", "C", "D", "E"], edges)); // 10

At step 4, find("A") goes from A to C, and find("B") goes from B to C. Both heads are C, so A-B is rejected.

When the nodes are numbers

Nodes can also be the numbers 0 to n - 1 (n is the number of nodes), as in the exercise, with edges written [u, v, weight]. The node numbers can be used as indexes, so parent can simply be an array: for (let i = 0; i < n; i++) parent[i] = i;. Everything else stays the same, and the limit is n - 1 edges.

Two small cases need no extra code. A duplicate edge (a second edge for the same pair of nodes) is rejected, because that pair is already one group. A graph with one node needs no edge at all, so its total is 0.

Prim: grow from one node

Prim's algorithm works another way: it starts from one node, for example A, so at first the tree holds only A. At each step, Prim takes the cheapest edge that joins the tree to a node outside it: A-C 2, then C-B 1, then B-D 5, then D-E 2. The total is 10 here too. To find the cheapest edge quickly, Prim usually uses a min-heap: a data structure that gives its smallest item quickly.

So the difference: Kruskal sorts all the edges and uses union-find, while Prim grows from one node with a min-heap. Both are greedy (always take the cheapest choice right now), and for MST this greedy approach is proven to always be right.

⚠️ An MST isn't the shortest route, and merging the wrong thing

TL;DR: An MST (minimum spanning tree) is a set of edges that joins all V nodes of a graph with no cycle, for the smallest total weight. For a connected graph, an MST always has V - 1 edges. Kruskal: sort the edges from the smallest weight up (sort((a, b) => a[2] - b[2])) and take them one by one, until there are V - 1 edges. Reject an edge whose two ends are already joined, that is, when find gives the same group head for both. If the heads differ, merge the two groups through their heads: parent[ra] = rb. Prim grows from one node with a min-heap. The total comes out the same.

⚡ MST: everything joined, smallest total

Guess first: an MST (minimum spanning tree) joins every node of a graph with no cycle, for the smallest total weight. If a graph has 5 nodes, how many edges does its MST have?

4, always V - 1 (V is the number of nodes) when all the nodes can be joined. With fewer, some node isn't joined yet. With more, there is surely a cycle.

Meaning: An MST is like power cables to every village: the villages are nodes, the cables are edges, and a cable's length is its weight. There's no need for two lines to the same village.

⚡ Kruskal: cheapest first, reject cycles

Write:

function find(x) {
  while (parent[x] !== x) {
    x = parent[x];
  }
  return x;
}

for (const [a, b, w] of sorted) {
  const ra = find(a);
  const rb = find(b);
  if (ra === rb) continue; // already one group: a cycle

  parent[ra] = rb; // merge the two groups
  total += w;
  used++;
  if (used === nodes.length - 1) break;
}

Meaning: Kruskal's algorithm finds an MST by taking the edges one by one from the smallest weight up (sorted). Nodes that are already joined are recorded as one group in parent (this is called union-find), and find looks up a node's group head: the node whose parent is itself. ra and rb are the heads of the edge's two ends. If they're the same, the edge makes a cycle and is skipped. If not, the heads get merged, parent[ra] = rb, not the nodes. The loop stops once V - 1 edges are used.

⚡ Kruskal or Prim?

Meaning: Kruskal sorts every edge and uses union-find. Prim's algorithm starts from one node, then keeps taking the cheapest edge to a node not joined yet, with a min-heap. Both are greedy, and the MST total comes out the same. Remember too: you find the shortest route with Dijkstra, not with an MST.

What you will learn