DISCRETE MATH • GRAPH THEORY

Kruskal's and Prim's Algorithms (Conceptual)

Two greedy strategies for constructing minimum spanning trees in weighted graphs.

Historical Context & Motivation

The problem of connecting a collection of points at minimum total cost predates the formal language of graph theory itself. In the early twentieth century, as engineers planned telephone networks, electrical grids, and transportation routes, a recurring question emerged: given a set of locations and the costs of connecting each pair, how can one wire (or pave, or pipe) them all together while spending as little as possible? The mathematical abstraction of this question is the minimum spanning tree (MST) problem — one of the most elegant and practically significant problems in combinatorial optimization.

A spanning tree of a connected, undirected graph G = (V, E) is a subgraph that includes every vertex of G and is itself a tree — that is, it is connected and acyclic. Among all spanning trees of a weighted graph, the MST is one whose total edge weight is minimized. Two celebrated greedy algorithms — one due to Kruskal and one due to Prim — solve this problem efficiently, yet they adopt fundamentally different strategies for selecting edges.

1926
Borůvka's Algorithm
Czech mathematician Otakar Borůvka devised the first known MST algorithm while designing an efficient electrical network for Moravia. His method iteratively adds the cheapest edge leaving each connected component.
1930
Jarník's Contribution
Vojtěch Jarník independently described a vertex-growing approach to MST construction, which would later be rediscovered and popularized by Robert Prim.
1956
Kruskal's Algorithm Published
Joseph Kruskal published his edge-sorting algorithm in the Proceedings of the American Mathematical Society. His approach processes edges globally in non-decreasing order of weight, adding each edge that does not form a cycle.
1957
Prim's Algorithm Published
Robert C. Prim rediscovered Jarník's approach and published it in the Bell System Technical Journal. The algorithm grows a single tree from an arbitrary start vertex by always attaching the nearest vertex not yet in the tree.
1975
Union-Find Optimization
Robert Tarjan's work on the union-find (disjoint set) data structure with path compression and union by rank provided Kruskal's algorithm with a nearly linear-time cycle-detection subroutine, solidifying its practical efficiency.

The central question these algorithms answer is deceptively simple: Which edges should we keep? In a dense graph on n vertices, there can be as many as n(n − 1)/2 edges, yet any spanning tree uses exactly n − 1 of them. Kruskal and Prim each provide a principled, greedy strategy for identifying those n − 1 edges while guaranteeing global optimality — a remarkable property that rests on the structural theory of matroids and the cut property of minimum spanning trees.

Core Principles & Definitions

Both Kruskal's and Prim's algorithms belong to the family of greedy algorithms — procedures that build a solution incrementally by making the locally optimal choice at each step. What makes MST algorithms remarkable among greedy methods is that this local greediness is provably sufficient to achieve a global optimum, a guarantee that does not hold for most combinatorial optimization problems. The theoretical foundation for this guarantee involves two key structural properties of spanning trees: the cut property and the cycle property.

1

Spanning Tree

A subgraph of G that is connected, acyclic, and includes every vertex. Any spanning tree of a graph with n vertices has exactly n − 1 edges. This edge count characterizes trees among connected graphs.
2

Cut Property

For any cut (S, V \ S) of the graph, the minimum-weight edge crossing the cut belongs to some MST. This property justifies Prim's strategy of always selecting the cheapest edge connecting the growing tree to the remaining vertices.
3

Cycle Property

For any cycle in the graph, the maximum-weight edge on the cycle does not belong to any MST (assuming distinct weights). This property justifies rejecting edges that would form a cycle, as Kruskal's algorithm does.
4

Greedy Strategy

At each iteration, select the locally best edge that preserves the tree invariant (no cycles for Kruskal; connectivity growth for Prim). The matroid structure of the graphic matroid guarantees that the greedy approach yields the global minimum.
5

Union-Find (Disjoint Set)

A data structure that maintains a partition of elements into disjoint sets, supporting efficient union and find operations. Kruskal's algorithm uses it to determine in nearly constant amortized time whether two vertices are already connected.
KEY TAKEAWAY
Think of constructing an MST as planning a road network between cities. Kruskal's approach is like a highway commission that ranks every possible road segment by cost and approves them one at a time, skipping any that would create a redundant loop. Prim's approach is like starting construction from a single city and always extending the network to the nearest unconnected city. Both strategies end up building the same cheapest possible network — the minimum spanning tree — but they differ in whether they think globally about edges or locally about vertices.

Visual Explanation — Kruskal's Algorithm

Kruskal's algorithm operates on the global edge list. It begins by sorting all edges in non-decreasing order of weight, then examines them one by one. Each candidate edge is added to the growing forest if and only if it connects two different components; otherwise, it is discarded because it would create a cycle. The process terminates once n − 1 edges have been accepted. The diagram below illustrates this procedure on a small weighted graph with six vertices.

The diagram shows a weighted graph on six vertices. Solid colored edges represent the five edges selected for the MST by Kruskal's algorithm. Dashed edges were either rejected (they would have created a cycle) or were not needed once n − 1 = 5 edges had been accepted. Note that edge A–B with weight 4 is skipped because A and B already belong to the same component at that point.

Observe that Kruskal's algorithm does not grow a single connected component from the start. Instead, it begins with a forest of n isolated vertices and gradually merges components by adding edges in weight order. The critical check at each step — "does this edge connect two different components?" — is performed efficiently using the union-find data structure. When two endpoints share the same component representative, the edge is rejected. When they differ, the edge is accepted and their components are merged. This global, edge-centric perspective contrasts sharply with Prim's vertex-centric, single-tree growth, which we visualize next.

Mathematical Framework

The correctness of both algorithms rests on a common theoretical foundation. To prove that a greedy edge-selection procedure produces a minimum spanning tree, we invoke the cut property and the cycle property, which together characterize MST membership for individual edges. These properties are not merely algorithmic heuristics — they are structural theorems about weighted graphs that hold regardless of which algorithm one employs.

SPANNING TREE EDGE COUNT
|E(T)| = |V| − 1
Any spanning tree T of a connected graph G = (V, E) contains exactly |V| − 1 edges. This follows from the fact that a tree on n vertices has n − 1 edges, a standard result provable by induction on n.
CUT PROPERTY (THEOREM)
For any cut (S, V \ S), the unique minimum-weight crossing edge e* belongs to every MST.
A cut (S, V \ S) is a partition of V into two non-empty subsets. If all edge weights are distinct, the lightest edge crossing the cut must appear in every MST. Proof: suppose MST T does not contain e*. Then T contains some other edge f crossing the cut. Swapping f for e* yields a tree of strictly lower weight, contradicting T's minimality.
CYCLE PROPERTY (THEOREM)
For any cycle C in G, the unique maximum-weight edge eₘₐₓ on C belongs to no MST.
If we add a non-tree edge to an MST, a unique cycle is formed. The heaviest edge on that cycle can be removed without disconnecting the tree, yielding one of equal or lower weight. Thus, the heaviest edge on any cycle is never needed in an MST (assuming distinct weights).
KRUSKAL TIME COMPLEXITY
O(|E| log |E|) = O(|E| log |V|)
Sorting the edge list dominates: O(|E| log |E|). Since |E| ≤ |V|², we have log |E| ≤ 2 log |V|, so this simplifies to O(|E| log |V|). The union-find operations across all edges add at most O(|E| · α(|V|)), where α is the inverse Ackermann function, effectively constant.
PRIM TIME COMPLEXITY
O(|E| log |V|) with a binary heap; O(|E| + |V| log |V|) with a Fibonacci heap
Prim's algorithm performs |V| extract-min operations and up to |E| decrease-key operations on a priority queue. With a binary heap, both operations cost O(log |V|), giving O((|V| + |E|) log |V|) = O(|E| log |V|) for connected graphs. A Fibonacci heap reduces decrease-key to amortized O(1), yielding the improved bound.

An important corollary of the cut and cycle properties is the following: if all edge weights are distinct, the MST is unique. When weights are not distinct, multiple MSTs may exist, but both Kruskal's and Prim's algorithms will still produce a valid one. The choice between the two algorithms often comes down to graph density: Kruskal's is favored for sparse graphs where |E| is close to |V|, while Prim's (with a Fibonacci heap) excels on dense graphs where |E| approaches |V|².

Detailed Breakdown — Prim's Algorithm

While Kruskal's algorithm is edge-centric, Prim's algorithm is vertex-centric. It maintains a single growing tree, starting from an arbitrary vertex, and at each iteration it adds the lightest edge that connects a vertex inside the tree to one outside it. This is a direct application of the cut property: at every step, the partition (tree vertices, non-tree vertices) defines a cut, and Prim's algorithm selects the minimum-weight crossing edge. The following diagram traces the algorithm on the same six-vertex graph used for Kruskal's illustration, starting from vertex A.

Prim's algorithm grows a single tree from vertex A. At each step, it identifies all edges crossing the cut between tree vertices (green) and non-tree vertices, then selects the minimum-weight one. The final MST has the same total weight of 13, but the edge-selection order differs from Kruskal's: here, E–F (weight 5) is added in step 3 because it is the cheapest edge leaving the tree {A, D, E} at that point, whereas Kruskal's algorithm adds it later.
💡 Same MST, Different Order
When all edge weights are distinct, both algorithms produce the same MST — the unique one guaranteed by the distinctness of weights. When weights are not distinct, they may produce different valid MSTs, but both will have the same total weight. The order in which edges are added, however, is almost always different because the algorithms use fundamentally different selection criteria.

Worked Example

Consider a connected, weighted graph G with vertices {A, B, C, D, E} and edge set {(A,B,3), (A,C,1), (B,C,7), (B,D,5), (B,E,4), (C,D,6), (D,E,2)}. We will trace both Kruskal's and Prim's algorithms to find the MST.

Kruskal's Algorithm Trace

Kruskal's Algorithm on G = ({A,B,C,D,E}, 7 edges)
1
Step 1 — Sort All Edges by WeightList all edges in non-decreasing weight order: (A,C,1), (D,E,2), (A,B,3), (B,E,4), (B,D,5), (C,D,6), (B,C,7). We need n − 1 = 4 edges for the MST.
Sorted edge list ready. Forest: {A}, {B}, {C}, {D}, {E}
2
Step 2 — Process Edge (A,C,1)Vertices A and C are in different components. Adding this edge merges them. Components: {A,C}, {B}, {D}, {E}.
Accept (A,C,1). MST edges so far: {(A,C,1)}. Running weight = 1.
3
Step 3 — Process Edge (D,E,2)D and E are in different components. Accept the edge. Components: {A,C}, {B}, {D,E}.
Accept (D,E,2). MST edges: {(A,C,1), (D,E,2)}. Running weight = 3.
4
Step 4 — Process Edge (A,B,3)A is in {A,C} and B is in {B}. Different components, so we accept. Components: {A,B,C}, {D,E}.
Accept (A,B,3). MST edges: {(A,C,1), (D,E,2), (A,B,3)}. Running weight = 6.
5
Step 5 — Process Edge (B,E,4)B is in {A,B,C} and E is in {D,E}. Different components — accept. This merges everything into one component: {A,B,C,D,E}. We now have 4 edges = n − 1, so the algorithm terminates.
Accept (B,E,4). Final MST = {(A,C,1), (D,E,2), (A,B,3), (B,E,4)}. Total weight = 10.

Prim's Algorithm Trace (Starting from A)

Prim's Algorithm on G, starting vertex A
1
Step 1 — Initialize Tree with Vertex ATree vertices: {A}. Edges crossing the cut ({A}, {B,C,D,E}): (A,B,3), (A,C,1). The minimum-weight crossing edge is (A,C,1).
Add vertex C. Tree: {A,C}. MST edges: {(A,C,1)}.
2
Step 2 — Grow from {A, C}Edges crossing the cut ({A,C}, {B,D,E}): (A,B,3), (B,C,7), (C,D,6). Minimum is (A,B,3).
Add vertex B. Tree: {A,B,C}. MST edges: {(A,C,1), (A,B,3)}.
3
Step 3 — Grow from {A, B, C}Crossing edges: (B,D,5), (B,E,4), (C,D,6), (B,C,7) — but (B,C) has both endpoints in the tree, so it is excluded. Minimum is (B,E,4).
Add vertex E. Tree: {A,B,C,E}. MST edges: {(A,C,1), (A,B,3), (B,E,4)}.
4
Step 4 — Grow from {A, B, C, E}Only vertex D remains. Crossing edges: (B,D,5), (C,D,6), (D,E,2). Minimum is (D,E,2).
Add vertex D. Tree: {A,B,C,D,E}. Final MST edges: {(A,C,1), (A,B,3), (B,E,4), (D,E,2)}. Total weight = 10.
🔍 Observation
Both algorithms produced the same MST with total weight 10 and edge set {(A,C,1), (D,E,2), (A,B,3), (B,E,4)}, but the selection order differed. Kruskal's added D–E second (following the global sort order), while Prim's added it last (because D was the final vertex absorbed into the tree).

Comparison — Kruskal's vs. Prim's

Although both algorithms solve the same problem and are guaranteed to produce an MST, they differ significantly in strategy, data structure requirements, and practical performance characteristics. The table below highlights the most important contrasts.

Kruskal's vs. Prim's — a head-to-head comparison
CriterionKruskal's AlgorithmPrim's Algorithm
StrategyEdge-centric: sort all edges globally, process in orderVertex-centric: grow a single tree from a start vertex
Key data structureUnion-Find (disjoint set) for cycle detectionPriority queue (min-heap or Fibonacci heap)
Time complexityO(|E| log |E|) = O(|E| log |V|)O(|E| log |V|) with binary heap; O(|E| + |V| log |V|) with Fibonacci heap
Best suited forSparse graphs (|E| close to |V|); edge listsDense graphs (|E| close to |V|²); adjacency matrices
Intermediate stateForest of trees that merge over timeSingle connected tree that grows
ParallelizabilityEdges in the same weight class can be considered in parallel (with care)Inherently sequential — each step depends on the current tree
Correctness basisCycle property: reject an edge only if it creates a cycleCut property: the lightest crossing edge of a cut belongs to the MST
KEY TAKEAWAY
Choosing between Kruskal's and Prim's is analogous to choosing between a batch-processing approach and a streaming approach in data engineering. Kruskal's sorts the entire workload (edge list) upfront and then processes items in order — ideal when the workload is small relative to the number of processors (sparse graph). Prim's maintains a dynamic frontier and continuously updates priorities — ideal when the adjacency structure is rich (dense graph) and an efficient priority queue is available.

Connection to Advanced Theory

Kruskal's and Prim's algorithms are foundational, but the MST problem connects to a rich web of advanced topics in combinatorics, algorithm design, and applied mathematics. Understanding these connections places the MST within its proper theoretical context and opens doors to more sophisticated techniques.

Advanced topics connected to minimum spanning trees
ConceptRelationship to MST
Matroid TheoryThe set of forests of a graph forms a graphic matroid. The greedy algorithm is optimal on any matroid — this is precisely why Kruskal's algorithm works. Matroid intersection generalizes MST to more constrained settings.
Steiner Tree ProblemUnlike MST, the Steiner tree need not span all vertices — it connects a designated subset of terminal vertices, possibly using intermediate (Steiner) vertices. This problem is NP-hard, but MST provides a 2-approximation for the metric Steiner tree.
Borůvka's AlgorithmA third MST algorithm that simultaneously selects the cheapest edge leaving each component. It has O(|E| log |V|) complexity and is naturally parallelizable, making it important in distributed computing and the design of near-linear-time randomized MST algorithms.
Minimum Bottleneck Spanning TreeInstead of minimizing total weight, minimize the maximum edge weight. Every MST is a minimum bottleneck spanning tree (though the converse is false), revealing that MSTs simultaneously optimize multiple objectives.
Dynamic MSTWhen edges are inserted or deleted from the graph, maintaining the MST efficiently requires advanced data structures such as Euler tour trees and link-cut trees. This is an active area of research in dynamic graph algorithms.

In practical applications, MST algorithms underpin network design (telecommunications, transportation, water distribution), clustering in machine learning (single-linkage clustering is equivalent to Kruskal's algorithm), image segmentation, and approximation algorithms for NP-hard problems like the traveling salesman problem. The 2-approximation for metric TSP works by doubling the MST edges to form an Eulerian multigraph, then shortcutting repeated vertices — a technique that elegantly bridges MST theory and combinatorial optimization.

Practice Problems

PROBLEM 1CONCEPTUAL
Explain why a greedy algorithm is guaranteed to produce the globally optimal solution for the MST problem, even though greedy approaches fail for most optimization problems. In your answer, reference either the cut property or the cycle property.
PROBLEM 2BASIC CALCULATION
Consider a graph with vertices {1, 2, 3, 4} and edges: (1,2,5), (1,3,8), (1,4,3), (2,3,10), (2,4,6), (3,4,4). Apply Kruskal's algorithm to find the MST. List the edges in the order they are selected and give the total MST weight.
PROBLEM 3INTERMEDIATE
Apply Prim's algorithm starting from vertex 1 on the same graph from Problem 2: vertices {1, 2, 3, 4}, edges (1,2,5), (1,3,8), (1,4,3), (2,3,10), (2,4,6), (3,4,4). Trace each step, identifying the cut edges and the one selected. Does the resulting MST match the one from Kruskal's algorithm?
PROBLEM 4APPLIED
A university campus has 6 buildings labeled A–F. The IT department wants to lay fiber optic cable to connect all buildings at minimum total cost. Costs (in thousands of dollars) for possible cable routes are: A–B: 12, A–C: 8, A–D: 15, B–C: 10, B–E: 7, C–D: 9, C–E: 14, D–F: 6, E–F: 11. Use either algorithm to find the MST and determine the minimum cabling cost.
PROBLEM 5CRITICAL THINKING
Suppose a connected weighted graph G has some edges with equal weights. Prove or disprove: Kruskal's and Prim's algorithms must always produce the same MST on G. If they can differ, construct a small counterexample and explain why both outputs are valid.

Summary

The minimum spanning tree problem asks for the least-cost connected subgraph spanning all vertices of a weighted graph. Kruskal's algorithm solves it by sorting all edges globally and accepting each one that does not create a cycle, using a union-find data structure for efficient component tracking. Prim's algorithm grows a single tree from an arbitrary start vertex, always attaching the nearest unconnected vertex via a priority queue. Both are greedy algorithms whose correctness is guaranteed by the cut property and the cycle property of spanning trees.

In terms of performance, Kruskal's runs in O(|E| log |V|) and excels on sparse graphs, while Prim's achieves O(|E| + |V| log |V|) with a Fibonacci heap and is preferred for dense graphs. When all edge weights are distinct, the MST is unique and both algorithms produce it; when weights are not distinct, multiple MSTs may exist but all share the same optimal total weight. These algorithms connect to broader themes in matroid theory, network design, clustering, and approximation algorithms for NP-hard problems.

Varsity Tutors • Discrete Math • Kruskal's and Prim's Algorithms (Conceptual)