AlgoViz

Prim's algorithm

medium 22 min

A 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

0:00 / 5:05

Prim's algorithm in 75 seconds

1:25Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

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

    heappush and heappop in O(log⁡n)O(\log n), 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 G=(V,E)G = (V, E). A spanning tree is a subset of edges that connects all ∣V∣|V| vertices with no cycle, which always means exactly ∣V∣−1|V| - 1 edges. A minimum spanning tree (MST) is a spanning tree whose total weight is as small as possible.

The MST, formally

T∗=arg⁡min⁡T ∈ T(G)  w(T),w(T)=∑(u,v)∈Tw(u,v),∣T∣=∣V∣−1T^{*} = \arg\min_{T \,\in\, \mathcal{T}(G)} \; w(T), \qquad w(T) = \sum_{(u,v) \in T} w(u, v), \qquad |T| = |V| - 1
T(G)\mathcal{T}(G) is the set of all spanning trees. A complete graph on nn vertices has nn−2n^{n-2} of them (Cayley's formula): 1,296 for n=6n = 6, far too many to try.

Spanning tree facts

PropertyWhy it holds
Exactly V−1V - 1 edgesFewer leaves a vertex cut off; one more always closes a cycle
Exactly one path between any two verticesTwo paths would form a cycle
Removing any edge disconnects itThat edge was the only path between its two sides
The MST is unique if all weights are distinctOtherwise several trees can tie on total weight

Why greedy works

The cut property

A cut splits the vertices into two non-empty groups, SS and V∖SV \setminus S. 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

∀ S⊂V, S≠∅:e=arg⁡min⁡(u,v): u∈S, v∉Sw(u,v)  ⟹  e∈some MST\forall\, S \subset V,\ S \neq \varnothing: \quad e = \arg\min_{(u,v):\ u \in S,\ v \notin S} w(u,v) \;\Longrightarrow\; e \in \text{some MST}
The lightest edge crossing any cut is safe to add. With distinct weights it is in the MST.

Proof by exchange

Swap the heavier crossing edge for the lighter one; the tree never gets worse.

The exchange in one line

w(T′)=w(T)+w(e)−w(f)≤w(T)since w(e)≤w(f)w(T') = w(T) + w(e) - w(f) \le w(T) \quad \text{since } w(e) \le w(f)
Interview version: "if the lightest crossing edge were missing, I could swap it in for the other crossing edge on its cycle and not increase the weight."

The other half

The cycle property and ties

Cycle property

e=arg⁡max⁡e′∈Cw(e′) on a cycle C, weights distinct  ⟹  e∉MSTe = \arg\max_{e' \in C} w(e') \text{ on a cycle } C, \text{ weights distinct} \;\Longrightarrow\; e \notin \text{MST}
The heaviest edge on any cycle can always be dropped. In the network graph, cycle 1-2-4 has weights 9, 4, 3, so 1-2 (9) is never used.
  • 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

Prim in four moves
  1. 1Seedtree = {start}
  2. 2Offerpush edges out of the tree
  3. 3Choosepop the cheapest crossing edge
  4. 4Growadd its new vertex
Repeat: back to Seed

The loop runs until the tree has all $V$ vertices, which takes $V - 1$ successful pops.

Lazy Prim's main loop

Lazy: old edges stay in the heap and are skipped when popped, instead of being updated in place.

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.

StepPopTree afterHeap after pushesTotal
0–A3 A-C, 4 A-B0
13 A-CA, C1 C-B, 4 A-B, 4 C-D, 5 C-E3
21 C-BA, C, B2 B-D, 4 A-B, 4 C-D, 5 C-E4
32 B-D+ D2 D-E, 4 A-B, 4 C-D, 5 C-E, 6 D-F6
42 D-E+ E1 E-F, 4 A-B, 4 C-D, 5 C-E, 6 D-F8
51 E-Fall six4 entries left, all stale9
Step 2 is the interesting one: C-B (1) beats A-B (4), so B joins through C. A-B is now stale and never used.

Implementation

Lazy Prim with a min-heap

Python
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)   # 9
The version to write in an interview. graph maps each vertex to a list of (neighbour, weight).
Edit and run it in your browser

Key implementation details

  • Min-heap

    Hands back the lightest crossing edge in O(log⁡V)O(\log V).

  • 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 EE.

The derivation

T(V,E)=E⏟pushes⋅O(log⁡E)+E⏟pops⋅O(log⁡E),log⁡E≤log⁡V2=2log⁡V  ⟹  T=O(Elog⁡V)T(V, E) = \underbrace{E}_{\text{pushes}} \cdot O(\log E) + \underbrace{E}_{\text{pops}} \cdot O(\log E), \qquad \log E \le \log V^{2} = 2 \log V \;\Longrightarrow\; T = O(E \log V)
Often written O((V+E)log⁡V)O((V + E) \log V); for a connected graph E≥V−1E \ge V - 1, so the two are the same. Space is O(E)O(E) for the heap, O(V+E)O(V + E) with the adjacency list.

Every way to run Prim

VersionPriority structureTimeBest for
Lazy (this page)binary heap of edgesO(Elog⁡V)O(E \log V)Interviews, sparse graphs
Eager, indexed heapheap of vertices with decrease-keyO(Elog⁡V)O(E \log V), heap holds ≤V\le VLarge sparse graphs, less memory
Array of keysplain list, scannedO(V2)O(V^2)Dense graphs, adjacency matrices
Fibonacci heapO(1)O(1) amortised decrease-keyO(E+Vlog⁡V)O(E + V \log V)Theory; rarely worth it in practice
Python's 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 VV keys, so the total is V⋅V=O(V2)V \cdot V = O(V^2) whatever EE is.

Python
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])
Array Prim on an adjacency matrix (0 = no edge). The original app's dense graph gives total 8.
Edit and run it in your browser

One round of eager Prim

This is Dijkstra's loop with one change: the key is the single edge weight w(u,v)w(u, v), not dist[u]+w(u,v)\text{dist}[u] + w(u, v).

Choosing

Prim vs Kruskal

AspectPrim'sKruskal's
ApproachGrow one tree from a vertexSort all edges, merge a forest
FocusVertex-focusedEdge-focused
Data structurePriority queue (min-heap)Union-find
TimeO(Elog⁡V)O(E \log V) heap, O(V2)O(V^2) arrayO(Elog⁡E)=O(Elog⁡V)O(E \log E) = O(E \log V) for the sort
Best forDense graphs (array version), adjacency listsSparse graphs, edge lists, already sorted edges
Partial resultAlways one connected treeA forest that joins up at the end
Disconnected inputMST of the start's component onlyA minimum spanning forest, naturally
Same proof, two ways to pick the cut: Prim always cuts around its own tree, Kruskal cuts around whichever two trees the next edge joins.

Two strategies, one MST

With distinct weights both end at the same MST. Read the full method in Kruskal's algorithm.

Dense vs sparse

Pick the version by E against V²

The crossover

Elog⁡V⏟heap<V2⏟array  ⟺  E<V2log⁡V\underbrace{E \log V}_{\text{heap}} < \underbrace{V^{2}}_{\text{array}} \iff E < \frac{V^{2}}{\log V}
At V=1,000V = 1{,}000: a sparse graph with E=3,000E = 3{,}000 costs about 30,000 heap steps against 1,000,000 array steps; a complete graph with E=499,500E = 499{,}500 costs about 5,000,000 heap steps against 1,000,000.

Which MST algorithm?

First check the problem really is an MST, then let the graph's shape choose the version.

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.

Sources