Minimum Spanning Trees

Connect all vertices at minimum total edge cost with Kruskal's and Prim's algorithms and understand the cut property behind them.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Union-Find (Disjoint Set Union), Heaps and Priority Queues

A spanning tree connects all V vertices of an undirected graph using exactly V - 1 edges with no cycles. A minimum spanning tree (MST) has the smallest possible total weight. Think of laying cable or roads to connect every city as cheaply as possible.

Kruskal's algorithm

Sort edges by weight, then add each edge if it connects two different components (checked with union-find). Stop after V - 1 edges. O(E log E), dominated by sorting. Easiest to code when you have an edge list.

Prim's algorithm

Grow the tree from a start vertex: repeatedly add the cheapest edge leaving the current tree, using a min-heap. O(E log V). Natural for adjacency lists and dense graphs (an O(V^2) array version works for complete graphs like "connect all points").

Why they work

The cut property: for any split of vertices into two groups, the lightest edge crossing the split belongs to some MST. Both algorithms repeatedly pick such an edge, which is a classic greedy proof.

Variations

  • Min Cost to Connect All Points (complete graph, Prim's is efficient).
  • Checking which edges are critical or pseudo-critical.
  • Maximum spanning tree by sorting descending.

Pitfall: MST is about total weight, not shortest paths. The path between two nodes in an MST is not necessarily their shortest path.

Key concepts

  • Spanning tree definition
  • Kruskal's algorithm
  • Prim's algorithm
  • Cut property
  • MST vs shortest path tree
  • Critical edges in MST

Mini project

Implement both Kruskal and Prim and verify they give the same total on random graphs, then solve: Min Cost to Connect All Points, Connecting Cities With Minimum Cost, CSES Road Reparation, and Find Critical and Pseudo-Critical Edges in MST.

Check yourself

Why does the path between two vertices in an MST not have to be the shortest path between them?

Free resources