Discrete Mathematics and Combinatorics

Minimum Spanning Trees With Kruskal's and Prim's Algorithms

Work one network through both classic algorithms, see why greedy choices are safe, and learn what these trees cannot do.

Key takeaways

  • A spanning tree of a connected graph with n vertices uses exactly n − 1 edges and contains no cycle.
  • Kruskal adds the cheapest edge anywhere that creates no cycle, while Prim adds the cheapest edge leaving the tree built so far.
  • Both are justified by the cut property: the cheapest edge crossing a division of the vertices is safe to use.
  • If all edge weights are different, the minimum spanning tree is unique.
  • The tree minimizes total length, not the distance between any particular pair of vertices.

A minimum spanning tree is the cheapest set of edges that connects every vertex of a weighted network. Two classic methods find it. Kruskal's algorithm takes edges from cheapest to dearest, skipping any that would close a loop. Prim's algorithm grows one connected cluster, always adding the cheapest edge that reaches a new vertex.

Both are greedy: they make the best-looking choice at each step and never undo it. Greed fails in many problems, but here it is guaranteed to succeed, and the reason is short enough to follow.

The problem

Suppose six buildings, A to F, need to be linked by cable. A weighted graph records the possible links, each with a cost:

Edge Cost Edge Cost
AB 4 CE 10
AC 2 DE 2
BC 1 DF 6
BD 5 EF 3
CD 8

You want every building connected, directly or through others, at the smallest total cost. A solution never needs a cycle, because removing any edge of a cycle keeps everything connected and saves money (costs here are positive). So the answer is a tree that spans all six vertices, with five edges.

Trying every spanning tree is not practical in general. A complete network on n labeled vertices has n^(n−2) of them, which for just 10 vertices is 100 million.

Kruskal's algorithm

Joseph Kruskal published this method in 1956.

  1. List the edges in order of increasing weight.
  2. Take each edge in turn.
  3. Keep it if its two ends are not already connected by kept edges. Otherwise discard it.
  4. Stop when n − 1 edges have been kept.

On the example:

BC (1)   keep
AC (2)   keep
DE (2)   keep
EF (3)   keep
AB (4)   skip      A and B are already linked through C
BD (5)   keep      joins group {A, B, C} to group {D, E, F}
stop: 5 edges, total = 1 + 2 + 2 + 3 + 5 = 13

Midway, the kept edges form a forest of several separate pieces that gradually merge.

Prim's algorithm

Robert Prim described this method in 1957. Vojtěch Jarník had found it earlier, in 1930, and Edsger Dijkstra rediscovered it, so you may see other names.

  1. Start with any one vertex as the tree.
  2. Among all edges with exactly one end in the tree, choose the cheapest.
  3. Add that edge and its new vertex.
  4. Repeat until every vertex is included.

Starting at A:

Tree so far Cheapest edge leaving it Cost
A AC 2
A, C CB 1
A, B, C BD 5
A, B, C, D DE 2
A, B, C, D, E EF 3

The total is again 13, and the set of edges is the same. The order of discovery differs.

Two greedy routes to the same tree
Kruskal Considers all edges, cheapest first Grows many fragments that merge Rejects edges that close a cycle Needs a fast test for connected groups Prim Starts from one chosen vertex Keeps a single growing tree Picks the cheapest edge leaving the tree Needs the nearest outside vertex quickly VS Kruskal Considers all edges, cheapest first Grows many fragments that merge Rejects edges that close a cycle Needs a fast test for connected groups Prim Starts from one chosen vertex Keeps a single growing tree Picks the cheapest edge leaving the tree Needs the nearest outside vertex quickly

Why greed works here

A cut divides the vertices into two nonempty groups. An edge crosses the cut if it has one end in each.

Cut property. If edge e is strictly cheaper than every other edge crossing some cut, then every minimum spanning tree contains e.

The proof is an exchange argument. Suppose a spanning tree T omits e. Adding e to T creates a cycle. That cycle crosses from one group to the other through e, so it must cross back through some other edge f. Replace f with e. The result is still a spanning tree, and since e is cheaper than f, it costs less than T. So T was not minimum.

With ties, a slightly weaker statement holds: some minimum spanning tree contains a chosen cheapest crossing edge.

Each step of Prim picks the cheapest edge across the cut "inside the tree versus outside". Each kept edge in Kruskal is the cheapest edge across the cut that separates one of its fragments from the rest.

A mirror-image cycle property says that an edge strictly more expensive than every other edge on some cycle belongs to no minimum spanning tree. In the example, AB is the dearest edge of the triangle ABC, so it can be ignored from the start.

When is the answer unique?

If all edge weights are distinct, there is only one minimum spanning tree. Suppose there were two different ones, S and T. Take the cheapest edge that belongs to exactly one of them, and say it is e in S. Adding e to T creates a cycle, and that cycle must contain an edge f that is not in S, since S has no cycle. Because f also belongs to only one tree and e was the cheapest such edge, f costs more than e. Swapping f for e would make T cheaper, which is impossible.

With repeated weights, several trees may tie. In a square whose four sides all cost 1, removing any one side gives a minimum spanning tree of cost 3, so there are four of them. Every one has the same total, and in fact the same list of edge weights.

This explains why two students can run Kruskal's method correctly and draw different trees. Compare their totals, not their pictures.

Checking a proposed tree

You can test whether a given spanning tree T is minimum without building another. For each edge left out of T, look at the path in T between its ends. The left-out edge must cost at least as much as every edge on that path.

In the example, the tree is BC, AC, DE, EF and BD. Consider the left-out edge CD, with cost 8. The tree path from C to D runs through B and uses weights 1 and 5, both below 8. For CE, with cost 10, the path C, B, D, E uses 1, 5 and 2. For DF, with cost 6, the path D, E, F uses 2 and 3. For AB, with cost 4, the path A, C, B uses 2 and 1. All four pass, so the tree is optimal.

Making them fast

Kruskal's speed depends on testing whether two vertices are already connected. The union–find data structure keeps track of groups and merges them very quickly. Sorting the edges then dominates, giving time proportional to E log E for E edges.

Prim's speed depends on finding the cheapest edge out of the tree. With a binary heap, a structure that returns the smallest item efficiently, the time is proportional to E log V for a connected graph with V vertices. For dense graphs, where most pairs are joined, a plain array version taking time proportional to V² is hard to beat.

A third method, due to Otakar Borůvka in 1926, was motivated by planning an electrical network. Every fragment simultaneously grabs its cheapest outgoing edge, and the fragments merge in rounds. It suits parallel computation. With ties it needs a consistent tie-breaking rule to avoid creating cycles.

What the tree does not do

A minimum spanning tree keeps the total small. It does not keep individual journeys short. Picture a triangle with side costs 2, 2 and 3. The tree uses the two edges of cost 2, so the two vertices joined by the 3 edge are now 4 apart.

If you want shortest routes from a starting point, you need Dijkstra's algorithm. It looks much like Prim's, but it ranks vertices by total distance from the start instead of by the cost of one edge.

A tree also has no redundancy. Cutting any single cable splits the network, so real designs often add extra links.

Finally, you are not allowed to invent new junction points. If you may add them, the task becomes the Steiner tree problem, which is NP-hard. For three towns at the corners of an equilateral triangle, a junction at the center gives a shorter network than any two sides.

Where else the idea helps

  • Clustering. Build the tree for data points using distances, then delete the longest edges. The remaining pieces are the groups produced by single-linkage clustering.
  • Approximating tours. When distances obey the triangle inequality, walking around a minimum spanning tree and skipping repeats gives a round trip at most twice the optimal length. See the traveling salesperson problem.
  • Maximum spanning trees. Reverse the order of preference, and the same algorithms find the heaviest spanning tree.
  • Bottleneck routes. The tree path between two vertices makes the largest single edge on the route as small as possible.

For a wider view of when step-by-step greed succeeds and when it misleads, read greedy algorithms.

Common mistakes

Students often stop Kruskal early because the cheapest edges seem to touch every vertex. Touching is not connecting: you need n − 1 edges in a single piece. In Prim's method, a frequent slip is choosing an edge with both ends already inside the tree. And in either method, skipping an edge is permanent, since once its ends are connected they stay connected.

Written for 4Mathematics with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 45 articles in Discrete Mathematics and Combinatorics →

Latest news on this topic