Command Palette

Search for a command to run...

Module 27

Minimum Spanning Trees

Connect every node at the lowest total cost: the cut property, Kruskal with union-find, Prim with a heap, virtual nodes and critical edges.

Advanced 2 lessons 5 problems ~25 min of lessons

A spanning tree connects all n nodes of an undirected graph with exactly n − 1 edges and no cycles. A minimum spanning tree (MST) does it with the smallest total weight: the cheapest way to lay cables, pipes or roads so everything is connected.

This module explains why greedy choices are safe here (the cut property), then teaches Kruskal's algorithm (sort edges, add if no cycle, using union-find from Module 25) and Prim's algorithm (grow one tree with a heap, or with arrays on dense graphs). Problems add tricks like a virtual node for "build your own source" options and testing which edges every MST must contain.

Best after: Union-Find (DSU), Heaps and Priority Queues

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. MST on a complete graph: array-based Prim without building the edges.

  2. Kruskal on an edge list, returning −1 when the graph can't be connected.

  3. A virtual node turns "build a well here" options into ordinary edges, so the whole problem becomes one MST.

  4. Test an edge's role by rebuilding the MST without it and with it forced in.

  5. Two spanning structures sharing edges: take shared edges first, then each person's own.