Prim's algorithm
medium 22 minA minimum spanning tree connects every vertex of a weighted, undirected graph with the least total edge weight.
Video lesson · Chapter 1 of 7
Five dark lighthouses
Prim's algorithm in 75 seconds
1:25Reel
How it works
Step through the idea, or press Play.
Start with one vertex. The tree is {start}; every edge out of it goes on a min-heap
Understand it
Start here
Connect every city for the least money
You must link a set of cities with roads so that you can drive from any city to any other. Each possible road has a building cost. You do not need every road, only enough to connect everything, and you want the cheapest total. Prim's algorithm solves this by growing the network one road at a time, always choosing the cheapest road that reaches a new city.
What you already know
Weighted graphs
Vertices, edges with weights, adjacency lists. See Graphs: the basics.
Min-heaps
heappushandheappopin , smallest first. See Heap operations.Priority queues
Tuples ordered by their first field, lazy deletion of stale entries. See Priority queues.
The goal
What a minimum spanning tree is
Take a connected, undirected, weighted graph . A spanning tree is a subset of edges that connects all vertices with no cycle, which always means exactly edges. A minimum spanning tree (MST) is a spanning tree whose total weight is as small as possible.
The MST, formally
Spanning tree facts
| Property | Why it holds |
|---|---|
| Exactly edges | Fewer leaves a vertex cut off; one more always closes a cycle |
| Exactly one path between any two vertices | Two paths would form a cycle |
| Removing any edge disconnects it | That edge was the only path between its two sides |
| The MST is unique if all weights are distinct | Otherwise several trees can tie on total weight |
Why greedy works
The cut property
A cut splits the vertices into two non-empty groups, and . An edge crosses the cut if it has one end on each side. Prim's tree and the rest of the graph form a cut at every step.
Cut property
Proof by exchange
The exchange in one line
The other half
The cycle property and ties
Cycle property
Cut property: what to add
The lightest edge across a cut is safe. Prim uses the cut (tree, rest).
Cycle property: what to skip
The heaviest edge on a cycle is never needed. A stale heap entry would close a cycle.
Ties
Equal weights can give several MSTs with the same total. Any tie choice is fine.
The algorithm
Grow one tree, one vertex at a time
- 1Seedtree = {start}
- 2Offerpush edges out of the tree
- 3Choosepop the cheapest crossing edge
- 4Growadd its new vertex
The loop runs until the tree has all $V$ vertices, which takes $V - 1$ successful pops.
Lazy Prim's main loop
Worked example
Tracing the six-vertex graph
Vertices A to F, edges A-B 4, A-C 3, B-C 1, B-D 2, C-D 4, C-E 5, D-E 2, D-F 6, E-F 1. Start at A. The heap column lists entries smallest first, written as weight and edge.
| Step | Pop | Tree after | Heap after pushes | Total |
|---|---|---|---|---|
| 0 | – | A | 3 A-C, 4 A-B | 0 |
| 1 | 3 A-C | A, C | 1 C-B, 4 A-B, 4 C-D, 5 C-E | 3 |
| 2 | 1 C-B | A, C, B | 2 B-D, 4 A-B, 4 C-D, 5 C-E | 4 |
| 3 | 2 B-D | + D | 2 D-E, 4 A-B, 4 C-D, 5 C-E, 6 D-F | 6 |
| 4 | 2 D-E | + E | 1 E-F, 4 A-B, 4 C-D, 5 C-E, 6 D-F | 8 |
| 5 | 1 E-F | all six | 4 entries left, all stale | 9 |
Implementation
Lazy Prim with a min-heap
import heapqdef prim(graph, start): visited = {start} heap = [(w, start, v) for v, w in graph[start]] heapq.heapify(heap) mst, total = [], 0 while heap and len(visited) < len(graph): w, u, v = heapq.heappop(heap) if v in visited: continue # stale: v joined the tree earlier visited.add(v) mst.append((u, v, w)) total += w for nxt, wt in graph[v]: if nxt not in visited: heapq.heappush(heap, (wt, v, nxt)) return mst, totaledges = [("A", "B", 4), ("A", "C", 3), ("B", "C", 1), ("B", "D", 2), ("C", "D", 4), ("C", "E", 5), ("D", "E", 2), ("D", "F", 6), ("E", "F", 1)]graph = {v: [] for v in "ABCDEF"}for u, v, w in edges: graph[u].append((v, w)) graph[v].append((u, w))mst, total = prim(graph, "A")print(mst) # [('A', 'C', 3), ('C', 'B', 1), ('B', 'D', 2), ('D', 'E', 2), ('E', 'F', 1)]print(total) # 9graph maps each vertex to a list of (neighbour, weight).Key implementation details
Min-heap
Hands back the lightest crossing edge in .
Visited set
Stops a vertex from being added twice, which would close a cycle.
Lazy deletion
Old edges are not removed; they are skipped when popped.
Edge-based heap
Store
(weight, from, to)with the weight first, so the heap orders by weight.
Cost
Why lazy Prim is O(E log V)
Each undirected edge is pushed at most once: when the first of its ends joins the tree, the other end is still outside; when the second end joins, the first is already visited, so nothing is pushed. Each push and each pop costs the logarithm of the heap size, which is at most .
The derivation
Every way to run Prim
| Version | Priority structure | Time | Best for |
|---|---|---|---|
| Lazy (this page) | binary heap of edges | Interviews, sparse graphs | |
| Eager, indexed heap | heap of vertices with decrease-key | , heap holds | Large sparse graphs, less memory |
| Array of keys | plain list, scanned | Dense graphs, adjacency matrices | |
| Fibonacci heap | amortised decrease-key | Theory; rarely worth it in practice |
heapq has no decrease-key, so the lazy version is the usual choice there.Variant
Eager Prim: keys instead of edges
Keep one number per vertex: key[v], the cheapest edge from the tree to v so far, and parent[v], where that edge comes from. Pick the outside vertex with the smallest key, add it, then lower its neighbours' keys. With a plain list the pick is a scan of keys, so the total is whatever is.
def prim_dense(W): n = len(W) INF = float("inf") key = [INF] * n # cheapest edge into the tree parent = [-1] * n in_tree = [False] * n key[0] = 0 total = 0 for _ in range(n): u = min((v for v in range(n) if not in_tree[v]), key=lambda v: key[v]) in_tree[u] = True total += key[u] for v in range(n): if W[u][v] and not in_tree[v] and W[u][v] < key[v]: key[v] = W[u][v] parent[v] = u return total, parentW = [[0, 2, 3, 6, 5], [2, 0, 4, 1, 7], [3, 4, 0, 0, 2], [6, 1, 0, 0, 3], [5, 7, 2, 3, 0]]print(prim_dense(W)) # (8, [-1, 0, 0, 1, 2])One round of eager Prim
Choosing
Prim vs Kruskal
| Aspect | Prim's | Kruskal's |
|---|---|---|
| Approach | Grow one tree from a vertex | Sort all edges, merge a forest |
| Focus | Vertex-focused | Edge-focused |
| Data structure | Priority queue (min-heap) | Union-find |
| Time | heap, array | for the sort |
| Best for | Dense graphs (array version), adjacency lists | Sparse graphs, edge lists, already sorted edges |
| Partial result | Always one connected tree | A forest that joins up at the end |
| Disconnected input | MST of the start's component only | A minimum spanning forest, naturally |
Two strategies, one MST
Dense vs sparse
Pick the version by E against V²
The crossover
Which MST algorithm?
Use Prim when
- You are building a minimum-cost network: roads, cable, pipes.
- The graph is dense, or given as an adjacency matrix.
- You want a single connected tree at every step, or must start from a specific vertex.
- The graph fits in memory as an adjacency list.
Consider something else when
- The graph is sparse and given as an edge list: Kruskal is simpler.
- The graph is disconnected: check connectivity first, or build a forest.
- You need shortest paths between vertices: that is Dijkstra or Floyd-Warshall, not an MST.
- Edges are directed: use Chu-Liu/Edmonds.
Recap
Key takeaways
Key points
- An MST connects all V vertices of a weighted undirected graph with V - 1 edges and the least total weight.
- Cut property: the lightest edge crossing any cut is in some MST. Prim applies it to the cut (tree, rest).
- Cycle property: the heaviest edge on a cycle is never needed.
- Lazy Prim: min-heap of (weight, from, to), mark visited on pop, skip stale entries.
- Each edge is pushed and popped at most once: O(E log V) time, O(E) heap space.
- Array Prim with key and parent lists is O(V²): best for dense graphs and all-pairs inputs.
- Prim grows one tree from a vertex; Kruskal sorts edges and merges a forest with union-find.
- On the simple graph from A the MST is A-C, C-B, B-D, D-E, E-F with weight 9.