Spanning Tree and Minimum Spanning Tree — Kruskal's and Prim's Algorithm
A Spanning Tree of a connected, undirected graph is a subgraph that includes all the vertices with the minimum number of edges needed to keep the graph connected, and without forming any cycles. A Minimum Spanning Tree (MST) is a spanning tree with the smallest possible total edge weight.
Kruskal's Algorithm
Kruskal's builds the MST by sorting all edges by weight and adding them one at a time, skipping any edge that would form a cycle (checked using a Union-Find/Disjoint Set structure), until all vertices are connected.
def kruskal(num_vertices, edges):
parent = list(range(num_vertices))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(x, y):
parent[find(x)] = find(y)
mst = []
for u, v, w in sorted(edges, key=lambda e: e[2]):
if find(u) != find(v):
union(u, v)
mst.append((u, v, w))
return mst
Prim's Algorithm
Prim's builds the MST by starting from an arbitrary vertex and repeatedly adding the cheapest edge that connects a vertex already in the MST to a vertex outside it, typically using a priority queue.
import heapq
def prim(num_vertices, adj):
visited = [False] * num_vertices
min_heap = [(0, 0)] # (weight, vertex)
total_cost = 0
while min_heap:
weight, u = heapq.heappop(min_heap)
if visited[u]:
continue
visited[u] = True
total_cost += weight
for v, w in adj[u]:
if not visited[v]:
heapq.heappush(min_heap, (w, v))
return total_cost
Complexity
| Algorithm | Time Complexity |
|---|---|
| Kruskal's (with Union-Find) | O(E log E) |
| Prim's (with binary heap) | O(E log V) |
Applications
- Network design — laying cables or pipelines at minimum cost.
- Approximation algorithms for problems like the Traveling Salesman Problem.
- Cluster analysis in machine learning.
Why Both Algorithms Give a Valid MST
Kruskal's and Prim's look different but both rely on the same guarantee, the cut property. It says that for any way of splitting the vertices into two groups, the cheapest edge crossing the split is safe to include in some minimum spanning tree. Kruskal's applies this globally — it always grabs the next cheapest edge anywhere, as long as it does not close a cycle. Prim's applies it locally — it always grabs the cheapest edge leaving the tree built so far. Because every edge they add is a safe edge, both finish with a tree of minimum total weight.
Kruskal vs Prim: Which Fits Your Graph
| Factor | Kruskal's | Prim's |
|---|---|---|
| Works on | Edge list, sorted by weight | Adjacency list with a heap |
| Strength | Sparse graphs (few edges) | Dense graphs (many edges) |
| Core helper | Union-Find (disjoint set) | Priority queue |
| Grows | A forest that merges into one tree | One tree outward from a start vertex |
For a sparse graph where edges are easy to list and sort, Kruskal's is natural. For a dense graph where a vertex connects to many others, Prim's with a heap tends to win. Both land near O(E log V), so the choice is usually about which structure your input already fits.
The Cut Property in Plain Words
Picture the vertices divided into "inside the tree" and "outside". Among all the roads connecting the two sides, the cheapest one can never be a mistake — leaving it out and using a pricier crossing would only raise the total. That is the intuition behind why greedily taking the cheapest safe edge keeps working all the way to a complete minimum tree.
- A spanning tree of
nvertices always has exactlyn - 1edges and no cycles. - The graph must be connected for a single spanning tree to exist; otherwise you get a spanning forest.
- In Kruskal's, the Union-Find structure is what detects a cycle quickly before an edge is added.
Takeaway: both algorithms are greedy and both are correct because every edge they add is justified by the cut property. Choose Kruskal's for sparse, edge-listed graphs and Prim's for dense ones, and remember the n - 1 edge rule as a quick sanity check.