Overview
Prim's algorithm also builds a minimum spanning tree, but grows a single tree outward from a start vertex. At each step it adds the cheapest edge that connects a vertex inside the tree to a vertex outside it, using a min-heap of candidate edges.
It resembles Dijkstra, except the heap key is the weight of the single connecting edge rather than the total distance from the source. For dense graphs, a simple O(V^2) version without a heap is often the fastest option.
Start at the power plant. Each day, connect the one town that is cheapest to reach from any town already powered. Keep going until every town has power.
When to use it
- Minimum spanning tree on a dense graph or complete graph (all pairs of points).
- The graph is given as an adjacency list or matrix rather than an edge list.
- You want to grow the tree incrementally from one vertex.
Problem patterns it solves
Recognize it when: all pairs of points are potential edges.
- 1584. Min Cost to Connect All Points
- 1135. Connecting Cities With Minimum Cost
Recognize it when: incremental expansion by the cheapest frontier edge.
- Minimum spanning tree from adjacency matrix
Where it is used in real software
Designing a cable network that grows from a central data center to all buildings at minimum cost.
Randomized Prim's algorithm generates perfect mazes by growing a tree of carved passages.
The MST gives a 2-approximation for the metric traveling salesman problem.
Key terms
- In-tree set
- Vertices already connected by the growing tree.
- Frontier edge
- An edge from an in-tree vertex to an outside vertex.
- key[v]
- Cheapest known edge weight connecting v to the tree (dense version).
- Lazy Prim
- Push edges into the heap and skip those leading to in-tree vertices.
How it works, step by step
- 1Start from any vertex
Mark it in the tree; push its edges into a min-heap.
- 2Pop the cheapest edge
If it leads to a vertex already in the tree, skip it.
- 3Add the new vertex
Add the edge weight to the total, mark the vertex in the tree.
- 4Push its edges
Add edges from the new vertex to outside vertices.
- 5Stop at V vertices
The tree is complete; if the heap empties first, the graph is disconnected.
Prim from A on the same graph as Kruskal
Edges: A-B 1, B-C 4, A-C 3, C-D 2, B-D 5
| Step | Pop edge | Added vertex | Heap after (candidates) | Total |
|---|---|---|---|---|
| Start | - | A | A-B 1, A-C 3 | 0 |
| 1 | A-B 1 | B | A-C 3, B-C 4, B-D 5 | 1 |
| 2 | A-C 3 | C | C-D 2, B-C 4, B-D 5 | 4 |
| 3 | C-D 2 | D | B-C 4, B-D 5 (both lead inside) | 6 |
NOWStep: Start | Pop edge: - | Added vertex: A | Heap after (candidates): A-B 1, A-C 3 | Total: 0
Same MST weight, 6, as Kruskal, but built by expanding one tree. Remaining heap entries point to vertices already in the tree and are discarded.
Implementation
// Lazy Prim with a heap (PriorityQueue from the Heap guide)function prim(n, graph) { // graph[u] = [[v, w], ...] const inTree = new Array(n).fill(false); const heap = new PriorityQueue((a, b) => a[0] - b[0]); heap.push([0, 0]); // [weight, vertex] let total = 0, count = 0; while (heap.size && count < n) { const [w, u] = heap.pop(); if (inTree[u]) continue; inTree[u] = true; total += w; count++; for (const [v, weight] of graph[u]) if (!inTree[v]) heap.push([weight, v]); } return count === n ? total : -1;} // O(V^2) dense Prim: best for complete graphs like 1584function minCostConnectPoints(points) { const n = points.length; const key = new Array(n).fill(Infinity); const inTree = new Array(n).fill(false); key[0] = 0; let total = 0; for (let step = 0; step < n; step++) { let u = -1; for (let v = 0; v < n; v++) if (!inTree[v] && (u === -1 || key[v] < key[u])) u = v; inTree[u] = true; total += key[u]; for (let v = 0; v < n; v++) { if (inTree[v]) continue; const d = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]); if (d < key[v]) key[v] = d; } } return total;}Complexity and performance
Good for sparse graphs.
Best for dense or complete graphs.
Graph and heap.
Trade-offs
Kruskal needs sorted edges and Union Find; Prim needs adjacency and a heap. On complete graphs with V points, O(V^2) Prim avoids creating V^2 edges and sorting them.
Same structure, different key: Prim uses the edge weight w, Dijkstra uses dist[u] + w.
Variants and related techniques
Keep one heap entry per vertex and update its key; fewer heap entries.
Pick a random frontier edge instead of the cheapest.
Common mistakes
- Using dist[u] + w as the key.
Fix: That is Dijkstra. Prim's key is only the connecting edge weight w.
- Not skipping in-tree vertices when popping.
Fix: Lazy Prim leaves stale edges in the heap; check inTree first.
Interview questions
How is Prim different from Dijkstra?
Both pop the smallest key from a heap. Prim's key is the weight of the edge connecting a vertex to the tree; Dijkstra's key is the total distance from the source.
Which MST algorithm would you use for 1,000 points on a plane?
O(V^2) Prim: it computes distances on the fly without building and sorting about 500,000 edges.
Practice problems
| Problem | Difficulty | What it trains |
|---|---|---|
| 1584. Min Cost to Connect All Points | Medium | Dense O(V^2) Prim. |
| 1135. Connecting Cities With Minimum Cost | Medium | Heap-based Prim. |
| Compare Prim and Kruskal on the same input | Medium | Equal totals, different order. |