AlgoFrames

Kruskal's algorithm

Kruskal’s algorithm builds a minimum spanning tree by taking edges from cheapest to most expensive, skipping any edge that would form a cycle.

Before you start: Disjoint set union: find, union, rank, path compression.

The idea

Six offices need cables so every office can reach every other one. Which cables give the lowest total cost?

A set of edges that joins every vertex with no cycle is a spanning tree. The cheapest one is the minimum spanning tree (MST).

Intuition

List the edges from cheapest to most expensive. The cheapest edge, A-C (1), goes in first.

Some MST contains the cheapest edge. Swapping it into any spanning tree never raises the cost.

After A-C and B-C, the edge A-B (3) would close a cycle. A and B are already joined, so skip it.

Keep going until 5 edges join the 6 vertices; A-B and B-D are skipped. A tree on V vertices always has V − 1 edges.

Complexity

Sorting the E edges costs O(E log E). The find calls after that are cheaper, so the total is O(E log E).

E log E and E log V grow alike, because E is at most V², and log V² = 2 log V.

This is the forest the Mechanics run built. Each find walks parent arrows to a root; attaching the smaller set keeps walks ≤ log V.

Path compression makes the walks even shorter. The forest uses O(V) space, and the sorted list uses O(E).

Pitfalls

On a new graph in two pieces, the edges run out early. The result is a spanning forest, so check for V − 1 edges.

On this small graph, equal weights allow more than one MST. Both choices give the same total weight, 5.

Tests that expect one exact edge list must fix a tie rule, such as input order.

Variations

Sort from heaviest to lightest and the same loop builds a maximum spanning tree. Here it weighs 29.

Prim grows one tree from a start vertex instead of merging many. From A it took A-C; the blue vertices B and E touch the tree.

Code

Pseudocode

sort edges by weight, cheapest first
make each vertex its own set
tree ← empty, total ← 0
for each edge (u, v, w) in sorted order
  a ← find(u), b ← find(v)
  if a = b: skip the edge
  attach the smaller set's root b under a
  add (u, v) to tree, total ← total + w
  if tree has V − 1 edges: stop
return tree, total

Python

def kruskal(n, edges):
    parent = list(range(n))
    size = [1] * n
    def find(x):
        while parent[x] != x:
            x = parent[x]
        return x
    tree, total = [], 0
    for u, v, w in sorted(edges, key=lambda e: e[2]):
        a, b = find(u), find(v)
        if a == b:
            continue
        if size[a] < size[b]:
            a, b = b, a
        parent[b] = a
        size[a] += size[b]
        tree.append((u, v))
        total += w
        if len(tree) == n - 1:
            break
    return tree, total

JavaScript

function kruskal(n, edges) {
  const parent = Array.from({ length: n }, (_, i) => i);
  const size = new Array(n).fill(1);
  const find = (x) => { while (parent[x] !== x) x = parent[x]; return x; };
  const sorted = edges.slice().sort((p, q) => p[2] - q[2]);
  const tree = [];
  let total = 0;
  for (const [u, v, w] of sorted) {
    let a = find(u), b = find(v);
    if (a === b) continue;
    if (size[a] < size[b]) [a, b] = [b, a];
    parent[b] = a;
    size[a] += size[b];
    tree.push([u, v]);
    total += w;
    if (tree.length === n - 1) break;
  }
  return { tree, total };
}

Cost at a glance

TimeO(E log E)
SpaceO(V)
InputConnected undirected weighted graph
OutputMinimum spanning tree

Practice problems (6)

MST edges in order Warm-up

Run Kruskal on this graph. First click the edge it looks at right after B-D. Then put the edges of the MST in the order Kruskal adds them.

Accept or reject? Warm-up

Kruskal has accepted A-C (1) and B-C (2). The next edge in sorted order is A-B (3). What does Kruskal do with it?

Implement Kruskal Standard

Return the total weight of a minimum spanning tree of the undirected graph graph. Return -1 when the graph is not connected.

graph.n is the number of vertices and graph.edges lists [u, v, w] triples.

Min cost to connect points Standard

Each point [x, y] must be joined to every other point, directly or through other points. Joining two points costs their Manhattan distance |x1 − x2| + |y1 − y2|. Return the minimum total cost.

Spot the bug: linking the wrong vertex Standard

This Kruskal should return the MST weight, or -1 for a graph that is not connected. It returns -1 for some connected graphs. Click the line with the bug, then fix it.

Critical and pseudo-critical edges Challenge

An edge is critical when removing it makes every MST heavier (or leaves the graph disconnected). An edge is pseudo-critical when it is in some MST but not critical.

Return [critical, pseudoCritical]: two lists of edge indices into edges. Any order inside each list is accepted.

Related topics

Next on the path: Prim's algorithm