GRAPHS / ALGORITHM BRIEF

Prim's algorithm

Prim's algorithm also builds a minimum spanning tree, but grows a single tree outward from a start vertex.

IntermediatePhase 05 / Topic 10 of 10Mental modelComplexityEdge cases
01

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.

Expanding a power grid from one plant

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.

02

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.
03

Problem patterns it solves

Dense MST

Recognize it when: all pairs of points are potential edges.

  • 1584. Min Cost to Connect All Points
  • 1135. Connecting Cities With Minimum Cost
Grow from a source

Recognize it when: incremental expansion by the cheapest frontier edge.

  • Minimum spanning tree from adjacency matrix
04

Where it is used in real software

Network cabling from a hub

Designing a cable network that grows from a central data center to all buildings at minimum cost.

Maze generation

Randomized Prim's algorithm generates perfect mazes by growing a tree of carved passages.

Approximation algorithms

The MST gives a 2-approximation for the metric traveling salesman problem.

05

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.
06

How it works, step by step

  1. 1
    Start from any vertex

    Mark it in the tree; push its edges into a min-heap.

  2. 2
    Pop the cheapest edge

    If it leads to a vertex already in the tree, skip it.

  3. 3
    Add the new vertex

    Add the edge weight to the total, mark the vertex in the tree.

  4. 4
    Push its edges

    Add edges from the new vertex to outside vertices.

  5. 5
    Stop at V vertices

    The tree is complete; if the heap empties first, the graph is disconnected.

07

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 1 / 4
StepPop edgeAdded vertexHeap after (candidates)Total
Start-AA-B 1, A-C 30
1A-B 1BA-C 3, B-C 4, B-D 51
2A-C 3CC-D 2, B-C 4, B-D 54
3C-D 2DB-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.

08

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;}
09

Complexity and performance

Heap versionO(E log V)

Good for sparse graphs.

Array versionO(V^2)

Best for dense or complete graphs.

SpaceO(V + E)

Graph and heap.

10

Trade-offs

Prim vs Kruskal

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.

Prim vs Dijkstra

Same structure, different key: Prim uses the edge weight w, Dijkstra uses dist[u] + w.

11

Variants and related techniques

Eager Prim with decrease-key

Keep one heap entry per vertex and update its key; fewer heap entries.

Randomized Prim for mazes

Pick a random frontier edge instead of the cheapest.

12

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.

13

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.

14

Practice problems

ProblemDifficultyWhat it trains
1584. Min Cost to Connect All PointsMediumDense O(V^2) Prim.
1135. Connecting Cities With Minimum CostMediumHeap-based Prim.
Compare Prim and Kruskal on the same inputMediumEqual totals, different order.