AlgoMaster Logo

Prim's Algorithm

9 min readUpdated May 30, 2026
Listen to this chapter
Unlock Audio

Prim's Algorithm grows a Minimum Spanning Tree (MST) from a single starting vertex, one edge at a time, always picking the cheapest edge that connects the existing tree to a vertex not yet in the tree. Kruskal's algorithm processes edges from cheapest to most expensive globally, while Prim's expands outward from a seed vertex.

Both produce the same MST (or one of equal cost if multiple MSTs exist), but they approach the problem differently. Prim's is vertex-centric. Kruskal's is edge-centric. This difference has real consequences for performance depending on whether the graph is dense or sparse.

What Is Prim's Algorithm?

Prim's Algorithm is a greedy algorithm for finding the Minimum Spanning Tree of a weighted, connected, undirected graph. It was developed by Vojtech Jarnik in 1930 and later rediscovered by Robert Prim in 1957.

The core idea:

  1. Start from any vertex. Add it to the MST.
  2. Look at all edges connecting the MST to vertices not yet in the MST.
  3. Pick the edge with the smallest weight.
  4. Add that edge and its new vertex to the MST.
  5. Repeat until all vertices are in the MST.

At every step, the algorithm maintains two sets: vertices already in the MST, and vertices not yet in the MST. It always selects the minimum-weight edge that crosses from one set to the other. This is the greedy choice, and we will prove later why it is safe.

In this snapshot, vertices A and B are in the MST. The algorithm examines all edges crossing the boundary: A-C (3), A-D (7), B-C (2), B-E (5). It picks B-C with weight 2, the cheapest crossing edge. Vertex C joins the MST, and the process continues.

How Prim's Works

Consider this weighted undirected graph with 5 vertices:

Step 1: Start at vertex A. Mark A as visited. Add all edges from A to the priority queue.

  • Priority Queue: {(A-C, 1), (A-B, 4)}
  • MST edges: {}
  • MST cost: 0

Step 2: Extract the minimum edge (A-C, weight 1). C is not visited, so add C to the MST. Add all edges from C to unvisited vertices.

  • Priority Queue: {(C-B, 2), (C-E, 3), (A-B, 4), (C-D, 8)}
  • MST edges: {A-C}
  • MST cost: 1

Step 3: Extract (C-B, weight 2). B is not visited, so add B. Add edges from B to unvisited vertices.

  • Priority Queue: {(C-E, 3), (A-B, 4), (B-D, 5), (C-D, 8)}
  • MST edges: {A-C, C-B}
  • MST cost: 3

Step 4: Extract (C-E, weight 3). E is not visited, so add E. Add edges from E to unvisited vertices.

  • Priority Queue: {(A-B, 4), (B-D, 5), (E-D, 6), (C-D, 8)}
  • MST edges: {A-C, C-B, C-E}
  • MST cost: 6

Step 5: Extract (A-B, weight 4). B is already visited. Skip it.

Extract (B-D, weight 5). D is not visited, so add D. All vertices are now in the MST.

  • MST edges: {A-C, C-B, C-E, B-D}
  • MST cost: 11

The final MST looks like this:

The algorithm skipped the edge A-B (weight 4) because B was already in the MST by the time we processed it. The priority queue may contain stale entries, and we skip them if the target vertex is already visited.

Prim's vs Dijkstra

Prim's and Dijkstra's shortest path algorithm share almost the same code structure. Both use a priority queue, both process one vertex at a time, and both greedily select the minimum from the queue.

The difference comes down to what value goes into the priority queue.

AspectDijkstraPrim's
PurposeShortest path from source to all verticesMinimum Spanning Tree
PQ storesTotal distance from source to vertexEdge weight connecting vertex to MST
Key updatedist[v] = dist[u] + weight(u,v)key[v] = weight(u,v)
AccumulatesPath distancesNo, only individual edge weights
Works with negative weights?NoYes (only edge weights matter)

In Dijkstra, when you relax an edge (u, v), you compute dist[u] + weight(u,v) and update if it is smaller than dist[v]. The distance accumulates as you travel further from the source.

In Prim's, when you examine an edge (u, v), you check whether weight(u,v) is smaller than the current key for v. There is no accumulation. Only the direct edge weight that connects v to the tree matters.

Implementation

Here is the full implementation of Prim's Algorithm using an adjacency list and a min-heap. The min-heap lets us extract the cheapest crossing edge in O(log n) time at each step instead of scanning every candidate edge.

Implementation details worth highlighting:

  • Lazy deletion: We do not remove stale entries from the priority queue. Instead, we check inMST[u] when we dequeue and skip vertices already in the MST. This is simpler than maintaining a decrease-key operation on the heap.
  • Starting vertex: We start from vertex 0 with weight 0. The first vertex added to the MST contributes 0 to the total cost, which is correct since the first vertex does not need an edge to join the tree.
  • Disconnected graphs: If the graph is disconnected, we cannot form an MST. The check edgesAdded != n handles this case.

Step-by-Step Walkthrough

Consider this larger graph with 7 vertices:

We start from vertex 0.

Iteration 1: Process vertex 0 (weight 0)

  • Mark vertex 0 as in MST. Cost = 0.
  • Add edges: (0-1, w=2), (0-2, w=4)
  • PQ: [(2,1), (4,2)]

Iteration 2: Process vertex 1 (weight 2)

  • Mark vertex 1 as in MST. Cost = 0 + 2 = 2.
  • Add edges: (1-2, w=3), (1-3, w=8)
  • PQ: [(3,2), (4,2), (8,3)]

Iteration 3: Process vertex 2 (weight 3)

  • Dequeue (3,2). Vertex 2 is not in MST, so process it. Cost = 2 + 3 = 5.
  • Add edges: (2-3, w=5), (2-4, w=1)
  • PQ: [(1,4), (4,2), (5,3), (8,3)]
  • Note: (4,2) is stale since vertex 2 is now in MST, but we leave it in the PQ.

Iteration 4: Process vertex 4 (weight 1)

  • Dequeue (1,4). Vertex 4 is not in MST. Cost = 5 + 1 = 6.
  • Add edges: (4-5, w=6), (4-6, w=9)
  • PQ: [(4,2), (5,3), (6,5), (8,3), (9,6)]

Iteration 5: Skip stale, then process vertex 3 (weight 5)

  • Dequeue (4,2). Vertex 2 is already in MST. Skip.
  • Dequeue (5,3). Vertex 3 is not in MST. Cost = 6 + 5 = 11.
  • Add edges: (3-5, w=7)
  • PQ: [(6,5), (7,5), (8,3), (9,6)]

Iteration 6: Process vertex 5 (weight 6)

  • Dequeue (6,5). Vertex 5 is not in MST. Cost = 11 + 6 = 17.
  • Add edges: (5-6, w=4)
  • PQ: [(4,6), (7,5), (8,3), (9,6)]

Iteration 7: Process vertex 6 (weight 4)

  • Dequeue (4,6). Vertex 6 is not in MST. Cost = 17 + 4 = 21.
  • All 7 vertices are now in the MST.

Final MST cost: 21

MST edges selected: 0-1 (2), 1-2 (3), 2-4 (1), 2-3 (5), 4-5 (6), 5-6 (4)

Proof of Correctness

Why does always picking the cheapest crossing edge produce the MST? The answer lies in the Cut Property.

Cut Property: For any cut (partition of vertices into two non-empty sets) of a graph, if an edge is the unique minimum-weight edge crossing the cut, then that edge belongs to every MST. If it is one of several minimum-weight edges crossing the cut, it belongs to at least one MST.

At each step, Prim's algorithm creates a natural cut: vertices in the MST vs. vertices not in the MST. The cheapest edge crossing this cut is safe to add because of the Cut Property.

Here is the proof by contradiction:

  1. Suppose Prim's selects edge e = (u, v) as the cheapest crossing edge, but e is not in any MST.
  2. Let T be an MST that does not contain e.
  3. Since T is a spanning tree, adding e to T creates exactly one cycle.
  4. This cycle must contain another edge e' that also crosses the cut (since u is in the MST and v is not, the cycle must cross back at some point).
  5. Since Prim's chose e as the cheapest crossing edge, weight(e) <= weight(e').
  6. Removing e' from T and adding e gives us a tree T' with weight(T') <= weight(T).
  7. Since T was an MST, weight(T') cannot be less than weight(T), so weight(T') = weight(T).
  8. This means T' is also an MST, and it contains e. This contradicts our assumption that e is not in any MST.

Therefore, the greedy choice is always safe, and Prim's algorithm produces an MST.

Prim's vs Kruskal's

Both algorithms solve the same problem (MST), but they take fundamentally different approaches. Choosing the right one depends on the graph structure.

AspectPrim'sKruskal's
ApproachVertex-based, grows from a seedEdge-based, picks globally cheapest edges
Data structurePriority Queue (min-heap)Union-Find (Disjoint Set Union)
Best forDense graphs (E close to V^2)Sparse graphs (E close to V)
Complexity (binary heap)O((V + E) log V)O(E log E)
Complexity (optimal)O(V^2) with adjacency matrixO(E * alpha(V)) with path compression
Edge list needed?No, works with adjacency listYes, needs all edges sorted
Starting vertexYes, starts from one vertexNo, processes edges globally
Multiple componentsFinds MST of one componentFinds MST forest of all components
Easier to implementSlightly more complex (PQ)Simpler (sort + union-find)

Either algorithm produces a valid MST. Prim's fits dense graphs, complete graphs, and adjacency-matrix input. Kruskal's fits sparse graphs, edge-list input, and disconnected graphs where you want an MST forest.

Complexity Analysis

Time Complexity

The time complexity depends on the implementation:

With Binary Heap (PriorityQueue): O((V + E) log V)

  • Each vertex is extracted from the PQ at most once: O(V log V)
  • Each edge causes at most one PQ insertion: O(E log V)
  • Total: O((V + E) log V)

For connected graphs where E >= V - 1, this simplifies to O(E log V).

With Adjacency Matrix (no heap): O(V^2)

  • For each of V iterations, we scan all V vertices to find the minimum: O(V) per iteration
  • Total: O(V^2)
  • This is better for dense graphs where E is close to V^2, because O(V^2) < O(V^2 log V).

With Fibonacci Heap: O(E + V log V)

  • This is theoretically optimal but rarely used in practice due to high constant factors and implementation complexity.

Space Complexity

  • O(V + E) for the adjacency list
  • O(V) for the inMST array
  • O(E) worst case for the priority queue (lazy deletion can accumulate stale entries)
  • Total: O(V + E)

Key Takeaways

  • Prim's builds a Minimum Spanning Tree by growing one tree from a starting vertex, repeatedly adding the cheapest edge that crosses from the tree to a vertex not yet included until all vertices are covered.
  • A min-priority-queue holds candidate crossing edges keyed by weight, so each step extracts the smallest crossing edge in logarithmic time instead of scanning every candidate.
  • The implementation uses lazy deletion, leaving stale entries in the queue and skipping any dequeued vertex already in the MST, and it reports a disconnected graph when fewer than n vertices get added.
  • Correctness follows from the cut property: the cheapest edge crossing the cut between MST and non-MST vertices belongs to some MST, which the proof by contradiction in this chapter establishes.
  • With a binary heap the time complexity is O((V + E) log V), simplifying to O(E log V) for connected graphs, while an adjacency-matrix version runs in O(V^2) and suits dense graphs.
  • Prim's is vertex-centric and works directly on an adjacency list without a sorted edge list, and unlike Dijkstra it compares the individual edge weight connecting a vertex to the tree rather than an accumulated path cost.