Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Minimum Spanning Trees & Union-Find

Kruskal, Prim and the cut property, with disjoint sets in near-constant time.

You must wire 30 buildings together with fiber at the least total cost. The complete graph on 30 vertices has 3028≈2.3×104130^{28} \approx 2.3 \times 10^{41} spanning trees, far too many to try, yet one greedy rule finds the cheapest: keep taking the cheapest link that does not close a loop. A one-paragraph exchange argument proves it, and a data structure with near-constant cost per operation makes it fast.

What you’ll learn

  • Define spanning trees and minimum spanning trees, and prove the cut property and the cycle property with exchange arguments.
  • Implement Kruskal's algorithm with union-find in O(mlog⁡m)O(m \log m) and Prim's algorithm with a binary heap in O(mlog⁡n)O(m \log n), and choose between them and the O(n2)O(n^2) array version of Prim by the density of the graph.
  • Implement union-find with union by size and path compression, prove that union by size keeps every tree's height at most log⁡2n\log_2 n, and state the near-constant amortized bound.
  • Recognize minimum-spanning-tree problems in disguise (connecting at minimum cost, virtual vertices, bottleneck routes, clustering) and tell them apart from shortest-path trees and Steiner trees.

Spanning trees and the cut property

A spanning tree of a connected undirected graph G=(V,E)G = (V, E) is a set of edges that connects all nn vertices without a cycle; it always has exactly n−1n - 1 edges. When every edge has a weight w(e)w(e), a minimum spanning tree (MST) is a spanning tree of least total weight w(T)=∑e∈Tw(e)w(T) = \sum_{e \in T} w(e). If GG is disconnected, the goal becomes a minimum spanning forest, one tree per component.

Brute force is hopeless. The 7-vertex graph in the widget below already has 168 spanning trees, and the complete graph on nn vertices has nn−2n^{n-2} of them (Cayley's formula). The algorithms in this lesson rest on one structural fact about cuts.

DerivationProof: an exchange argument
  1. T+e contains exactly one cycle, through eT + e \ \text{contains exactly one cycle, through } e

    Let TT be an MST that contains AA. If e=(u,v)∈Te = (u, v) \in T we are done. Otherwise adding ee to TT creates exactly one cycle: ee plus the tree path from vv back to uu.

  2. w(e)≤w(e′)w(e) \le w(e')

    uu and vv lie on opposite sides of the cut, so the tree path between them must cross it somewhere: it contains a crossing edge e′∈Te' \in T. Since AA respects the cut, e′∉Ae' \notin A, and since ee is light,

  3. w(T′)=w(T)−w(e′)+w(e)≤w(T)w(T') = w(T) - w(e') + w(e) \le w(T)

    Swap them. Removing e′e' breaks the only cycle, so T′=T−e′+eT' = T - e' + e is a spanning tree, it still contains AA, and it is no heavier than TT. So T′T' is an MST containing A∪{e}A \cup \{e\}.

Check your understanding

All edge weights of a connected graph are distinct. Which edges are guaranteed to be in its minimum spanning tree?

  1. The heaviest edge incident to each vertex
  2. The lightest edge incident to each vertex
  3. No edge is guaranteed; it depends on the whole graph
  4. The edges of a shortest-path tree from vertex 1
Show the answer

B. The lightest edge incident to each vertex

Take the cut that puts one vertex vv alone on its side, ({v},V∖{v})(\{v\}, V \setminus \{v\}). Its crossing edges are exactly the edges at vv, so the lightest of them is the unique light edge of that cut and belongs to every MST.

Kruskal’s algorithm: lightest edges first

Kruskal's algorithm (1956) sorts the edges by weight and scans them from lightest to heaviest, keeping an edge exactly when its two ends lie in different components of the forest built so far. It is a greedy algorithm: each choice is final.

Why it is correct. Suppose Kruskal keeps e=(u,v)e = (u, v), and let SS be the component of the current forest AA that contains uu. The cut (S,V∖S)(S, V \setminus S) is respected by AA. Any edge lighter than ee that crosses it was examined earlier, when its ends were in different components (components only grow), so it was kept, and then it would lie inside the forest, which no crossing edge does. So ee is a light edge of the cut, and the cut property says A∪{e}A \cup \{e\} still extends to an MST. By induction, the final n−1n - 1 edges form an MST.

Predict before you look

Run Kruskal by hand on these edges: A–C 1, D–F 2, B–D 3, B–F 4, D–E 5, C–D 6, A–B 7, C–E 8, E–F 9. What is the weight of the minimum spanning tree?

Show the answer

17

Keep A–C 1, D–F 2 and B–D 3; reject B–F 4, because B–D–F already connects B and F; keep D–E 5 and C–D 6, which joins {A,C}\{A, C\} to {B,D,E,F}\{B, D, E, F\}. That is n−1=5n - 1 = 5 edges, so the scan can stop: 1+2+3+5+6=171 + 2 + 3 + 5 + 6 = 17.

Cost. Sorting takes O(mlog⁡m)O(m \log m), and since m≤n2m \le n^2, log⁡m≤2log⁡n\log m \le 2 \log n, so this is O(mlog⁡n)O(m \log n). The scan asks mm times "are uu and vv already connected?" and merges two components n−1n - 1 times. Answering that question fast is the job of the next step's data structure; with it, the scan costs O(m α(n))O(m\, \alpha(n)), so sorting dominates. If the edges arrive already sorted, or have small integer weights that counting sort can order, Kruskal runs in near-linear time.

Union-find: are u and v already connected?

Union-find, also called a disjoint-set structure, keeps a partition of the elements 0,…,n−10, \dots, n - 1 under two operations: find(x) returns the representative of xx's set, and union(a, b) merges the sets of aa and bb. Each set is a tree of parent pointers whose root is the representative. A find walks up to the root; a union finds both roots and links one under the other. Kruskal's question becomes find(u) == find(v).

Linked carelessly, the trees degenerate. If every union puts the current root under a new element, the sets form a path, and a find from its far end walks n−1n - 1 pointers.

Path compression points every node on a find path straight at the root, so later finds from those nodes take one step. With both heuristics, any sequence of mm operations on nn elements takes O(m α(n))O(m\,\alpha(n)) time (Tarjan, 1975), where α\alpha is the inverse Ackermann function: α(n)≤4\alpha(n) \le 4 for every nn below a number vastly larger than the roughly 108010^{80} atoms of the observable universe. The bound is amortized: one find can still take Θ(log⁡n)\Theta(\log n) steps, but the total over any sequence is near-linear.

python
class DSU:
    def __init__(self, n):
        self.parent, self.size = list(range(n)), [1] * n
    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]   # path halving
            x = self.parent[x]
        return x
    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a == b:
            return False                       # already in one set
        if self.size[a] < self.size[b]:
            a, b = b, a
        self.parent[b] = a                     # smaller tree under the larger
        self.size[a] += self.size[b]
        return True

def kruskal(n, edges):
    """edges = [(w, u, v), ...] on vertices 0..n-1. Returns (weight, tree)."""
    dsu, total, tree = DSU(n), 0, []
    for w, u, v in sorted(edges):
        if dsu.union(u, v):                    # joins two components
            total += w
            tree.append((u, v, w))
    return total, tree                         # fewer than n - 1 edges: disconnected

The find is iterative, so there is no recursion limit to hit. Path halving points every other node on the path at its grandparent in a single pass; with union by size it has the same O(α(n))O(\alpha(n)) amortized bound as full compression (Tarjan & van Leeuwen, 1984). On the widget's graph, kruskal returns weight 25.

Prim’s algorithm: grow one tree

Prim's algorithm (Prim, 1957; found earlier by Jarník, 1930) grows a single tree from a start vertex, each time adding the lightest edge with exactly one end in the tree. Its correctness is the cut property with SS = the tree's vertices: the tree respects that cut, and the chosen edge is a light edge of it. The implementation is Dijkstra's algorithm with one change: a waiting vertex is keyed by its cheapest edge into the tree, not by a path length.

python
import heapq

def prim(n, adj, s=0):
    """adj[u] = [(v, w), ...], each edge listed at both ends.
    Returns the weight of a minimum spanning tree of s's component."""
    in_tree, total = [False] * n, 0
    heap = [(0, s)]                            # (weight of the edge into the tree, vertex)
    while heap:
        w, u = heapq.heappop(heap)
        if in_tree[u]:
            continue                           # stale entry: u joined the tree already
        in_tree[u] = True
        total += w
        for v, wv in adj[u]:
            if not in_tree[v]:
                heapq.heappush(heap, (wv, v))
    return total

Lazy deletion, as in Dijkstra's algorithm: an edge is pushed only by whichever end joins the tree first, so the heap receives at most m+1m + 1 entries and the total is O(mlog⁡n)O(m \log n) in the worst case. With a Fibonacci heap and decrease-key, Prim runs in O(m+nlog⁡n)O(m + n \log n) (Fredman & Tarjan, 1987).

SituationUseTime
an edge list, sparse graph (mm near nn)Kruskal with union-findO(mlog⁡m)O(m \log m)
adjacency listsPrim with a binary heapO(mlog⁡n)O(m \log n)
a dense graph, or all pairs of nn points (m≈n2/2m \approx n^2/2)Prim with an array of best edge costs and no heap: each step scans the array for the minimumO(n2)O(n^2)
edges already sorted, or small integer weightsKruskal, sorting by countingO(m α(n))O(m\,\alpha(n)) after sorting
parallel or distributed machinesBorůvka's rounds (see the Optimal lessons)O(log⁡n)O(\log n) rounds of O(m)O(m) work
The array version of Prim keeps, for each vertex outside the tree, the weight of its cheapest edge into the tree, and updates it from each new tree vertex's row of the adjacency matrix: nn rounds of O(n)O(n) work.
Check your understanding

You must connect n=5000n = 5000 points in the plane, and an edge between any two points costs their Euclidean distance (about 1.25×1071.25 \times 10^7 possible edges). Which approach is the most efficient?

  1. Kruskal: build the list of all pairs, sort it, and scan
  2. Prim with a binary heap over all pairs
  3. Prim with an array of best edge costs, computing distances on the fly
  4. Dijkstra's algorithm from point 0
Show the answer

C. Prim with an array of best edge costs, computing distances on the fly

The graph is complete, so O(n2)=2.5×107O(n^2) = 2.5 \times 10^7 simple steps with no edge list is the best fit. Kruskal and heap-based Prim are correct, but they pay an extra logarithmic factor on m≈1.25×107m \approx 1.25 \times 10^7 edges (roughly 10810^8 to 3×1083 \times 10^8 steps), and Kruskal must also store every pair.

Recognizing it

Signals. "Connect all of them at minimum total cost", "every pair must be able to reach each other, directly or not", "build roads, cables or pipes". Also: "make the heaviest link on the route as light as possible" (bottleneck), "split into kk groups that are as far apart as possible" (clustering), and "either build a facility here or connect to one that exists" (a virtual vertex). The answer always uses n−1n - 1 edges, and the constraints usually allow O(mlog⁡m)O(m \log m), or O(n2)O(n^2) when every pair of points is a possible edge.

Problem (in our words)Key ideaTime
Connect nn points with cable; a cable between two points costs their Manhattan distanceAn implicit complete graph: array Prim, computing each distance when neededO(n2)O(n^2)
Close roads to save maintenance while every city stays reachable; maximize the money savedKeep an MST and close the rest: saving = total weight − MST weightO(mlog⁡m)O(m \log m)
Some roads already exist; add the cheapest new roads that connect every cityUnion the existing roads first (they cost nothing), then run Kruskal on the candidatesO(mlog⁡m)O(m \log m)
Drive from one city to another so that the heaviest road on the route is as light as possibleThe path between them in an MST is a minimum-bottleneck path (proved in the Optimal lessons)O(mlog⁡m)O(m \log m), then O(n)O(n) per query
Split nn items into kk groups so that the closest two items in different groups are as far apart as possibleKruskal stopped when kk components remain: single-linkage clusteringO(mlog⁡m)O(m \log m)
Each row is a classic interview or contest problem. The third works because existing roads cost nothing: give them weight 0 and Kruskal takes them first, which is exactly what the pre-union does (with non-negative costs).

Common bugs.

  • Not checking that the result has n−1n - 1 edges: a disconnected input yields a forest, and the "answer" silently ignores some vertices.
  • Sorting the edges by their endpoints instead of their weight (put the weight first in each tuple).
  • Building Prim's adjacency lists with each undirected edge in one direction only.
  • A recursive find on 10510^5 or more elements in Python: the recursion limit. Write it as a loop.
  • Overflow in C++: 10510^5 edges of weight up to 10910^9 need a 64-bit total (long long).
  • Union-find with neither union by size nor compression: adversarial inputs make each find Θ(n)\Theta(n).
  • Assuming the MST is unique when weights tie, or comparing your tree with an expected one edge by edge.
Check your understanding

Each of nn towns needs electricity. Town ii can build its own generator for gig_i, or be joined by a power line to another town jj for cijc_{ij}; a town joined to a town with power has power too. How do you find the cheapest plan?

  1. Build a generator in the town with the smallest gig_i, then take a shortest-path tree from it
  2. Add a virtual "power plant" vertex joined to each town ii by an edge of weight gig_i, and find an MST of the n+1n + 1 vertices
  3. It is a Steiner tree problem, so only an approximation is possible
  4. Compute a maximum flow from the cheapest generator to every town
Show the answer

B. Add a virtual "power plant" vertex joined to each town ii by an edge of weight gig_i, and find an MST of the n+1n + 1 vertices

A plan is a set of generators and lines in which every town is connected to some generator. Merge all generators into one virtual vertex: then a plan is exactly a spanning tree of the n+1n + 1 vertices (redundant lines can be dropped), and its cost is the tree's weight. The MST is the cheapest plan, and it may build several generators.

Key takeaways

  • Cut property: the lightest edge across any cut that the chosen edges respect is safe to add. Cycle property: an edge strictly heavier than the rest of some cycle is in no MST. With distinct weights the MST is unique.
  • Kruskal sorts the edges and keeps those that join two components: O(mlog⁡m)=O(mlog⁡n)O(m \log m) = O(m \log n), with union-find answering "already connected?".
  • Prim grows one tree, always adding the lightest edge that leaves it: O(mlog⁡n)O(m \log n) with a binary heap, O(n2)O(n^2) with an array, which is best for dense graphs.
  • Union-find with union by size (or rank) keeps trees at height ≤log⁡2n\le \log_2 n; with path compression as well, mm operations take O(m α(n))O(m\,\alpha(n)) time, where α(n)≤4\alpha(n) \le 4 for any practical nn.
  • Signals: connect everything at minimum total cost, minimize the largest edge used, split into well-separated groups, or add a virtual vertex for "build here or connect". A shortest-path tree and a Steiner tree are different problems.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

All weights are distinct, and the edge ee is the heaviest edge of some cycle. Can ee belong to the minimum spanning tree?

  1. Yes, if ee is a bridge
  2. Only if the cycle has an odd number of edges
  3. No: an MST containing ee could swap it for a lighter edge of the cycle
  4. Yes, if ee is the lightest edge at one of its endpoints
Show the answer

C. No: an MST containing ee could swap it for a lighter edge of the cycle

Deleting ee from an MST TT splits TT into two sides, and the rest of the cycle must cross between them with an edge e′e' lighter than ee. Then T−e+e′T - e + e' is a lighter spanning tree, a contradiction. This is the cycle property.

Question 2

On a connected graph with distinct weights, Kruskal's and Prim's algorithms...

  1. build the same tree, possibly adding its edges in different orders
  2. build different trees of the same total weight
  3. add the same edges in the same order, from lightest to heaviest
  4. agree only when the graph is dense
Show the answer

A. build the same tree, possibly adding its edges in different orders

With distinct weights the MST is unique, so both must return it. The order differs: Kruskal adds edges by increasing weight, while Prim only considers edges leaving its tree, so on the widget's graph it adds C–D 5 before D–E 2.

Question 3

Union-find uses union by size but no path compression, on n=1024n = 1024 elements. In the worst case, how many parent pointers can a single find follow?

  1. 1023
  2. 32
  3. 10
  4. 1
Show the answer

C. 10

A tree of height hh built by union by size has at least 2h2^h elements, so h≤log⁡21024=10h \le \log_2 1024 = 10. Pairing elements, then pairs of pairs, and so on, reaches exactly height 10.

Question 4

You must delete edges from a connected weighted graph until it is a tree, keeping the total weight of the remaining edges as large as possible. What works?

  1. Nothing greedy works; it needs dynamic programming
  2. Kruskal's algorithm scanning the edges from heaviest to lightest
  3. Dijkstra's algorithm from the heaviest edge
  4. Kruskal's algorithm as usual, then keep the edges it rejected
Show the answer

B. Kruskal's algorithm scanning the edges from heaviest to lightest

A maximum spanning tree is a minimum spanning tree for the weights −w(e)-w(e), and negating weights just reverses the scan order. The cut and cycle properties hold with "heaviest" in place of "lightest".

Go deeper

Further reading

  • J. B. Kruskal, "On the shortest spanning subtree of a graph and the traveling salesman problem," Proceedings of the American Mathematical Society 7(1) (1956), 48–50.
  • R. C. Prim, "Shortest connection networks and some generalizations," Bell System Technical Journal 36(6) (1957), 1389–1401.
  • R. E. Tarjan, "Efficiency of a good but not linear set union algorithm," Journal of the ACM 22(2) (1975), 215–225.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 19 and 21.