M27 · Minimum Spanning Trees

Minimum Spanning Trees: Cut and Cycle Properties, Kruskal and Prim

A minimum spanning tree connects every node of a weighted undirected graph with the least total edge weight. Two short facts, the cut property and the cycle property, say which edges are always safe to take and which are always safe to drop. Kruskal’s algorithm turns them into a loop over sorted edges with union-find; Prim’s algorithm grows one tree from a start node with a heap.

~45 minAdvancedC# · Python · Java · C++
Curriculum: M27 Minimum Spanning Trees · 1 of 1 lessons available

You will be able to

  • Define spanning trees and forests, and say why a spanning tree of n nodes has exactly n − 1 edges.
  • State the cut property and the cycle property, including what changes when weights tie.
  • Trace Kruskal’s algorithm with union-find, explaining every accepted and every rejected edge with one of the two properties.
  • Describe Prim’s algorithm with a binary heap and lazy deletion, and compare it with Kruskal on sparse and dense graphs.
  • Derive O(E log E) for Kruskal and O(E log V) for heap-based Prim, and recognise a minimum spanning forest when the graph is disconnected.
  • Tell a minimum spanning tree apart from a shortest-path tree with a counterexample.

Helpful before this lesson

  • M23 Graph Fundamentals — Graph vocabulary and representations, and how density changes the right choice.
  • M21 Heaps and Priority Queues — The array-backed heap, sift operations, O(n) heapify and heap sort.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

The problem

You have a set of sites and the cost of every possible direct link between two of them: cables between buildings, pipes between tanks, roads between villages. You want every site connected, directly or through others, at the lowest total cost. Redundant links are wasted money, so the answer never contains a cycle.

In graph terms: given a connected, undirected graph with weighted edges, a spanning tree is a subset of edges that connects all n nodes and has no cycle. A minimum spanning tree (MST) is a spanning tree whose total weight is as small as possible.

Three facts about trees are used throughout:

  • A tree on n nodes has exactly n − 1 edges. Fewer cannot connect everything; one more always closes a cycle.
  • Adding any edge to a spanning tree creates exactly one cycle.
  • Removing any edge of a tree splits it into exactly two components.

If the graph is disconnected, no spanning tree exists. The natural answer is then a minimum spanning forest: one minimum spanning tree per connected component, n − c edges for c components. Kruskal produces it without any change.

This module comes after union-find on purpose: Kruskal's algorithm is the classic use of that structure, and the lab below reuses the exact same union-find (union by rank, path compression).

Two properties that make greedy safe

Both MST algorithms in this lesson are greedy: they commit to an edge and never take it back. That is only correct because of two properties. A cut is a split of the nodes into two non-empty groups S and V \ S; an edge crosses the cut if it has one endpoint on each side.

Cut property. For any cut, a minimum-weight edge crossing it belongs to some minimum spanning tree. If it is the only lightest crossing edge, it belongs to every MST.

Why. Take an MST T that does not contain the light crossing edge e = (u, v). Adding e to T closes a cycle. That cycle goes from u's side to v's side through e and must come back across the cut somewhere else, through some tree edge f. Swap them: T − f + e is still a spanning tree, and since w(e) ≤ w(f) its weight is no larger. So an MST with e exists.

Cycle property. For any cycle, a maximum-weight edge on it can be left out: some MST avoids it. If it is the only heaviest edge on the cycle, no MST contains it.

Why. If an MST T contains the heavy edge f, removing f splits T into two parts. The rest of the cycle connects those parts again, so some other cycle edge e crosses between them. T − f + e is a spanning tree, and w(e) ≤ w(f), so it is no heavier.

Both arguments are exchange arguments: swap one edge for another and show the result is no worse. The same technique proves the greedy interval-scheduling rule in the Greedy module.

Kruskal's algorithm

Kruskal looks at edges from lightest to heaviest and keeps an edge unless it would close a cycle:

sort edges by weight (ties: input order)
make every node its own set            # union-find
tree = []
for each edge (u, v, w) in sorted order:
    if tree has n − 1 edges: stop      # nothing more can be added
    if find(u) == find(v): reject      # already connected → would close a cycle
    else: union(u, v); tree.append(edge)

Union-find answers "are u and v already connected by chosen edges?" in near-constant time, which is exactly the question the loop asks. The lab shows the graph with each edge's weight, the sorted list in front in scan order, and a second lane holding the tree as it grows. Each node is tagged with its union-find root, so nodes with the same tag are already in one component.

Why every decision is correct

  • Accept. When (u, v) is accepted, u and v are in different components. Let A be u's component, and cut the graph into A and everything else. Every lighter edge crossing this cut has already been examined, and it would have been accepted (its endpoints were in different components), which would have made A larger. So no lighter edge crosses the cut: (u, v) is a lightest crossing edge, and the cut property says it is safe.
  • Reject. When (u, v) is rejected, chosen edges already connect u and v, so (u, v) closes a cycle with them. Every chosen edge was examined earlier and is at most as heavy, so (u, v) is a heaviest edge on that cycle, and the cycle property says some MST does without it.

A worked trace

The lab's Seven nodes, cycles rejected preset has eleven edges. Sorted by weight (ties in input order): 0–3:5, 2–4:5, 3–5:6, 0–1:7, 1–4:7, 1–2:8, 4–5:8, 1–3:9, 4–6:9, 5–6:11, 3–4:15.

Step Edge Roots Decision Tree weight
1 0–3 (5) different accept 5
2 2–4 (5) different accept 10
3 3–5 (6) different accept 16
4 0–1 (7) different accept 23
5 1–4 (7) different accept: joins {0, 1, 3, 5} and {2, 4} 30
6 1–2 (8) same reject: cycle 1–4–2–1 30
7 4–5 (8) same reject: cycle 4–1–0–3–5–4 30
8 1–3 (9) same reject: cycle 1–0–3–1 30
9 4–6 (9) different accept: 6 edges, done 39

After step 9 the tree has n − 1 = 6 edges, so 5–6 and 3–4 are never examined: the lab fades them and its Edges examined metric stops at 9. The total, 39, is what the shared fixture records for all four languages.

Ties, negative weights and uniqueness

  • Ties. When several edges share a weight, more than one MST can exist. They all have the same total weight; only the edge set differs. This lab breaks ties by input order (the Equal weights preset), and so do the four implementations, which is why one fixture can pin the exact edges.
  • Distinct weights mean a unique MST. With no ties, every accepted edge was the only lightest edge across its cut, so it is in every MST.
  • Negative weights are fine. Both properties only compare weights; nothing adds them along a path. The Negative weights preset takes the −3 edge first. (Contrast Dijkstra, which breaks with negative edges.) A maximum spanning tree is the same algorithm with the order reversed, or with every weight negated.

Prim's algorithm

Prim grows a single tree from a start node. At every step it adds the lightest edge leaving the tree, which is the cut property applied to the cut (tree, rest). With a binary heap and lazy deletion, the same trick the Dijkstra lesson uses:

inTree[*] = false
push every edge of the start node onto a min-heap keyed by weight
inTree[start] = true
while the heap is not empty and the tree has fewer than n − 1 edges:
    (w, u, v) = pop the lightest edge        # u is in the tree
    if inTree[v]: continue                   # stale: both ends already in the tree
    inTree[v] = true; add (u, v) to the tree
    push every edge (v, x) with inTree[x] = false

Prim never needs union-find: "is v already in the tree?" is a boolean per node, because there is only one tree. On a disconnected graph it spans only the start node's component; run it again from an unvisited node to build a forest.

This lesson's lab and code cover Kruskal only. Prim's heap mechanics (push, pop, stale entries) are the ones you can step through in the Dijkstra lab; the difference is the key: Prim orders the heap by the weight of the single edge into the tree, Dijkstra by the total distance from the source.

Complexity

V nodes, E edges, adjacency lists.

Algorithm Time Extra space Best when
Kruskal (sort + union-find) O(E log E) = O(E log V) O(V + E): union-find arrays, sorted order sparse graphs, edges already in a list, or already sorted
Prim, binary heap, lazy deletion O(E log V) O(V + E): flags plus up to E heap entries sparse graphs given as adjacency lists
Prim, array of best edge weights, no heap O(V²) O(V) dense graphs, adjacency matrix
  • Kruskal: sorting costs O(E log E); since E ≤ V², log E ≤ 2 log V, so that is O(E log V). The loop makes at most 2E finds and V − 1 unions, O(E α(V)) with union by rank and path compression, which the sort dominates. If the edges arrive already sorted (or the weights are small integers you can counting-sort), the union-find part is all that remains.
  • The early stop after n − 1 accepted edges saves work in practice but not in the worst case: the heaviest edge may be the one that completes the tree.
  • On a dense graph (E close to V²), the O(V²) array version of Prim beats both O(E log V) = O(V² log V) versions.

Minimum spanning tree versus shortest-path tree

They are easy to confuse because both are trees chosen by weight. Take a triangle with edges 0–1:2, 1–2:2 and 0–2:3. The MST is {0–1, 1–2} with weight 4. The shortest-path tree from node 0 is {0–1, 0–2}, because the direct edge reaches 2 at cost 3 instead of 4. The MST minimises the sum of the chosen edges; a shortest-path tree minimises each node's distance from one source. Neither answers the other's question.

The teaching implementation

Kruskal.Run / kruskal sorts edge indices by (weight, index), then runs the loop above on the UnionFind class from the union-find lesson; it returns the accepted edge indices, the total weight, the number of components (1 for a spanning tree) and how many edges were examined. The listings are the files the tests run. Each language reads the shared fixture (forests, ties, negative weights, isolated nodes, an expensive bridge that must be taken) and compares the total weight with a brute force over every subset of edges on 500 random small graphs, checking that the result is acyclic and has one tree per component. Brute force is hopeless beyond about 20 edges, but it shares no logic with Kruskal, which makes it an honest check.

Language notes

None of the four standard libraries ships a union-find or an MST routine, so the code builds on the union-find lesson's class. What differs is sorting, and whether the sort keeps ties in order.

Language Sort used Notes
C# Array.Sort(int[], Comparison<int>) Introsort: not stable, so the comparison breaks ties by index explicitly. LINQ OrderBy(...).ThenBy(...) is stable but allocates. For Prim, PriorityQueue<TElement, TPriority> is a min-heap without decrease-key.
Python sorted(range(m), key=lambda i: (w[i], i)) Timsort is stable, so key=lambda i: w[i] alone would already keep ties in input order; the tuple makes the rule explicit. heapq provides the min-heap for Prim.
Java Arrays.sort(Integer[], Comparator) For object arrays the sort is documented as stable (a merge sort); for int[] it is a dual-pivot quicksort and not stable, which is why indices are boxed here. PriorityQueue with a comparator for Prim.
C++ std::ranges::sort Not stable; the comparator breaks ties by index. std::ranges::stable_sort would also work. std::priority_queue is a max-heap unless you pass std::greater<>.

Totals are accumulated in 64-bit integers (long / long long; Python integers do not overflow): a tree with many heavy edges can exceed the range of a 32-bit sum even when every single weight fits.

Common mistakes

  • Checking for cycles with a fresh DFS for every edge. It works, but costs O(V) per edge and O(E·V) overall. Union-find makes the same test nearly O(1).
  • Running it on a directed graph. MSTs are defined for undirected graphs. The directed analogue, a minimum spanning arborescence, needs a different algorithm (Chu–Liu/Edmonds).
  • Expecting a spanning tree from a disconnected graph. Check that the result has n − 1 edges (or that one component remains) before treating it as a tree.
  • Sorting with an unstable sort and expecting a particular tree. The weight is always minimal, but which of several equal-weight trees you get depends on tie-breaking.
  • Mixing up Prim and Dijkstra keys: Prim's key is the weight of one edge, not a path length.

Edge cases

  • One node and no edges: the empty tree, weight 0.
  • Isolated nodes: each one is its own component in the forest.
  • A single expensive bridge between two groups is in every spanning tree; Kruskal reaches it last.
  • Parallel edges: only the cheaper copy can be chosen; the lab accepts one edge per pair so it can draw them, and rejects self-loops (a loop is a one-edge cycle). The implementations tolerate both.

Worked practice

1. In the seven-node trace, why is 4–5 (weight 8) rejected while 4–6 (weight 9) is accepted?

Answer

When 4–5 comes up, nodes 4 and 5 are already connected through 4–1–0–3–5, so their union-find roots match and the edge would close a cycle (the cycle property: it is the heaviest edge on it). Node 6 has no chosen edge yet when 4–6 comes up, so the roots differ: 4–6 is the lightest edge crossing the cut between {6} and the rest, and the cut property makes it safe.

2. A connected graph has 50 nodes and 1,200 edges. How many edges does every MST have, and how many edges does Kruskal examine at least?

Answer

Every spanning tree has 49 edges. Kruskal examines at least 49 (if the 49 lightest edges happen to be acyclic) and at most all 1,200 (if the edge that completes the tree is the heaviest of all).

3. All edge weights in a connected graph are different. Can two different MSTs exist?

Answer

No. Each edge Kruskal accepts is the unique lightest edge across a cut, and by the strict form of the cut property such an edge is in every MST. All n − 1 accepted edges are therefore in every MST, and an MST has only n − 1 edges.

4. You have 2,000 nodes and nearly every pair is connected (about 2 million edges). Kruskal, heap Prim or array Prim?

Answer

Array Prim: O(V²) = 4 million basic steps. Kruskal sorts 2 million edges, about 2·10⁶ · 21 ≈ 42 million comparisons, and heap Prim is in the same range. On a dense graph the heap's logarithm costs more than it saves.

5. Your colleague computes an MST of a road network and uses its paths for navigation. What goes wrong?

Answer

The MST minimises the total length of the roads kept, not the length of the path between two places. In the triangle 0–1:2, 1–2:2, 0–2:3 the MST route from 0 to 2 costs 4 while the direct road costs 3. Navigation needs a shortest-path algorithm such as Dijkstra.

Summary

  • A minimum spanning tree connects all n nodes with n − 1 edges of least total weight; a disconnected graph gets a minimum spanning forest.
  • Cut property: a lightest edge across any cut is safe to add. Cycle property: a heaviest edge on any cycle is safe to drop.
  • Kruskal: sort edges, keep each one unless union-find says its endpoints are already connected. O(E log E).
  • Prim: grow one tree, always adding the lightest edge leaving it, with a heap (O(E log V)) or an array (O(V²), better for dense graphs).
  • Ties allow several MSTs of equal weight; negative weights are fine; an MST is not a shortest-path tree.

Full implementation

Kruskal in four languages (on top of the union-find lab’s UnionFind class), each checked against one shared fixture (accepted edges in order with the weight-then-index tie-break, total weight, components and edges examined before the early stop, including forests, ties and negative weights) and 500 random graphs compared with a brute-force search over every edge subset.

namespace Bekadan.Dsa.Examples.Graphs;
 
/// <summary>Accepted edge indices (in acceptance order), total weight, number of trees in the forest and edges examined.</summary>
public sealed record SpanningForest(List<int> Edges, long TotalWeight, int Components, int Examined);
 
/// <summary>
/// Kruskal's minimum spanning tree on an undirected graph (WeightedEdge lists each
/// edge once). Edges are scanned by (weight, input index); the UnionFind class
/// (union by rank, path compression) rejects an edge whose endpoints are already
/// connected, because it would close a cycle. Stops once n - 1 edges are chosen.
/// A disconnected graph yields a minimum spanning forest. O(E log E) for the sort,
/// O(E α(V)) for the union-find work. Negative weights are fine.
/// </summary>
public static class Kruskal
{
    public static SpanningForest Run(int nodeCount, IReadOnlyList<WeightedEdge> edges)
    {
        var sets = new UnionFind(nodeCount);
        var tree = new List<int>();
        long total = 0;
        int examined = 0;
 
        int[] order = Enumerable.Range(0, edges.Count).ToArray();
        Array.Sort(order, (a, b) => edges[a].Weight != edges[b].Weight ? edges[a].Weight.CompareTo(edges[b].Weight) : a.CompareTo(b));
 
        foreach (int i in order)
        {
            if (tree.Count == nodeCount - 1)
                break; // a spanning tree has exactly n - 1 edges
            var e = edges[i];
            examined++;
            int ru = sets.Find(e.From);
            int rv = sets.Find(e.To);
            if (ru == rv)
                continue; // already connected: this edge would close a cycle
            sets.Union(e.From, e.To);
            tree.Add(i);
            total += e.Weight;
        }
        return new SpanningForest(tree, total, sets.Count, examined);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Graphs/Kruskal.cs

"""Kruskal's minimum spanning tree on an undirected graph (each edge listed once).
 
Edges are scanned by (weight, input index); UnionFind (union by rank, path
compression) rejects an edge whose endpoints are already connected, because it
would close a cycle. The scan stops once n - 1 edges are chosen. A disconnected
graph yields a minimum spanning forest. O(E log E) for the sort, O(E * alpha(V))
for the union-find work. Negative weights are fine.
"""
 
from dataclasses import dataclass
 
from dsa_examples.union_find import UnionFind
 
 
@dataclass
class SpanningForest:
    edges: list[int]  # accepted edge indices, in acceptance order
    total_weight: int
    components: int
    examined: int
 
 
def kruskal(node_count: int, edges: list[tuple[int, int, int]]) -> SpanningForest:
    sets = UnionFind(node_count)
    tree: list[int] = []
    total = 0
    examined = 0
 
    order = sorted(range(len(edges)), key=lambda i: (edges[i][2], i))
 
    for i in order:
        if len(tree) == node_count - 1:
            break  # a spanning tree has exactly n - 1 edges
        u, v, weight = edges[i]
        examined += 1
        ru, rv = sets.find(u), sets.find(v)
        if ru == rv:
            continue  # already connected: this edge would close a cycle
        sets.union(u, v)
        tree.append(i)
        total += weight
    return SpanningForest(tree, total, sets.count, examined)

Tested on CPython 3.14.0 · examples/python/dsa_examples/kruskal.py

package dev.bekadan.dsa.graphs;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
/**
 * Kruskal's minimum spanning tree on an undirected graph (each edge listed once). Edges are
 * scanned by (weight, input index); {@link UnionFind} (union by rank, path compression) rejects
 * an edge whose endpoints are already connected, because it would close a cycle. The scan stops
 * once n - 1 edges are chosen. A disconnected graph yields a minimum spanning forest.
 * O(E log E) for the sort, O(E α(V)) for the union-find work. Negative weights are fine.
 */
public final class Kruskal {
    private Kruskal() {
    }
 
    public record Edge(int from, int to, int weight) {
    }
 
    /** Accepted edge indices in acceptance order, total weight, trees in the forest, edges examined. */
    public record Result(List<Integer> edges, long totalWeight, int components, int examined) {
    }
 
    public static Result run(int nodeCount, List<Edge> edges) {
        UnionFind sets = new UnionFind(nodeCount);
        List<Integer> tree = new ArrayList<>();
        long total = 0;
        int examined = 0;
 
        Integer[] order = new Integer[edges.size()];
        Arrays.setAll(order, i -> i);
        Arrays.sort(order, (a, b) -> edges.get(a).weight() != edges.get(b).weight()
                ? Integer.compare(edges.get(a).weight(), edges.get(b).weight())
                : Integer.compare(a, b));
 
        for (int i : order) {
            if (tree.size() == nodeCount - 1) {
                break; // a spanning tree has exactly n - 1 edges
            }
            Edge e = edges.get(i);
            examined++;
            int ru = sets.find(e.from());
            int rv = sets.find(e.to());
            if (ru == rv) {
                continue; // already connected: this edge would close a cycle
            }
            sets.union(e.from(), e.to());
            tree.add(i);
            total += e.weight();
        }
        return new Result(tree, total, sets.count(), examined);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/graphs/Kruskal.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <numeric>
#include <vector>
 
#include "bekadan/dsa/union_find.hpp"
 
namespace bekadan::dsa {
 
struct UndirectedEdge {
    std::size_t from;
    std::size_t to;
    int weight;
};
 
struct SpanningForest {
    std::vector<std::size_t> edges;  // accepted edge indices, in acceptance order
    long long total_weight = 0;
    std::size_t components = 0;
    std::size_t examined = 0;
};
 
// Kruskal's minimum spanning tree on an undirected graph (each edge listed once). Edges are
// scanned by (weight, input index); UnionFind (union by rank, path compression) rejects an edge
// whose endpoints are already connected, because it would close a cycle. The scan stops once
// n - 1 edges are chosen. A disconnected graph yields a minimum spanning forest.
// O(E log E) for the sort, O(E α(V)) for the union-find work. Negative weights are fine.
inline SpanningForest kruskal(std::size_t node_count, const std::vector<UndirectedEdge>& edges) {
    UnionFind sets(node_count);
    SpanningForest result;
 
    std::vector<std::size_t> order(edges.size());
    std::iota(order.begin(), order.end(), std::size_t{0});
    std::ranges::sort(order, [&edges](std::size_t a, std::size_t b) {
        return edges[a].weight != edges[b].weight ? edges[a].weight < edges[b].weight : a < b;
    });
 
    for (const std::size_t i : order) {
        if (result.edges.size() + 1 == node_count) break;  // a spanning tree has exactly n - 1 edges
        const UndirectedEdge& e = edges[i];
        ++result.examined;
        const std::size_t ru = sets.find(e.from);
        const std::size_t rv = sets.find(e.to);
        if (ru == rv) continue;  // already connected: this edge would close a cycle
        sets.unite(e.from, e.to);
        result.edges.push_back(i);
        result.total_weight += e.weight;
    }
    result.components = sets.count();
    return result;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/kruskal.hpp

References