Minimum Spanning Trees

Connect all nodes at the lowest total cost with Kruskal's (sort edges plus DSU) or Prim's (min-heap) algorithm.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Disjoint Set Union (Union-Find), Shortest Paths

A minimum spanning tree connects all V nodes of a weighted undirected graph with V - 1 edges and the smallest total weight. It appears in OAs as "connect all cities at minimum cost".

Kruskal's algorithm

Sort edges by weight. For each edge, add it if its endpoints are in different DSU components. O(E log E). Easy to write once DSU is solid.

Prim's algorithm

Grow the tree from one node. Use a min-heap of edges leaving the tree; pop the cheapest edge to an unvisited node. O(E log V). Natural when the graph is given as an adjacency list or is dense (points on a plane).

Key ideas

  • Cut property: the cheapest edge crossing any cut belongs to some MST. This is why both greedy algorithms are correct.
  • If the graph is disconnected you get a minimum spanning forest; check that V - 1 edges were added.
  • MST also minimises the maximum edge on the path between two nodes, which helps in "minimum bottleneck" questions.

Classic problems

Min Cost to Connect All Points, Connecting Cities With Minimum Cost, Minimum Spanning Tree (GfG), Road Reparation (CSES), Find Critical and Pseudo-Critical Edges in MST.

Pitfalls

  • Applying MST to a directed graph (that needs different algorithms).
  • Confusing MST with shortest path trees; they are different.

You are ready to move on when you can implement both Kruskal's and Prim's and explain the cut property in two sentences.

Key concepts

  • Spanning tree definition
  • Kruskal's with DSU
  • Prim's with a min-heap
  • Cut property
  • MST vs shortest path tree
  • Critical edges

Mini project

Implement Kruskal's and Prim's on the same input and confirm equal totals, then solve: Min Cost to Connect All Points, Connecting Cities With Minimum Cost, Road Reparation (CSES), and Find Critical and Pseudo-Critical Edges in MST. Log time and pattern.

Check yourself

Why does Kruskal's algorithm need a DSU, and what would go wrong without one?

Free resources