~/Coding Clutch/article.md
DSA

Prim’s Algorithm for Minimum Spanning Tree: Full Guide

January 10, 2025 · 18 min read

Prim’s Algorithm for Minimum Spanning Tree: Complete Guide with Examples, Implementation, Complexity Analysis, and Real-World Applications

You have 20 offices and a price for laying cable between any two of them. Every office must be reachable from every other, and you want the cheapest total cable. That is a minimum spanning tree (MST) problem, and Prim’s algorithm solves it by growing one connected network a single cheapest link at a time.

In this guide, you’ll learn why the greedy choice is provably safe, how to trace the algorithm by hand, and how to write it in Python and C++ in both the heap version and the dense array version. You’ll also see the one bug that makes a “correct-looking” implementation return the wrong total, which patterns in a problem statement point to an MST, and 11 practice problems in rough order of difficulty.

Phase 1: The Problem

How do you connect every node of a weighted graph at the lowest total cost, and why can’t you just try everything?

The brute-force answer is to pick every possible set of V−1 edges, discard the sets that contain a cycle or leave a node disconnected, and keep the cheapest survivor. A spanning tree on V nodes has exactly V−1 edges, so this is correct. It is also hopeless: with E edges you are checking C(E, V−1) subsets, each needing an O(V) tree check.

Take a complete graph on 20 offices. That is 190 edges, and C(190, 19) is about 6.4 × 10²⁵ subsets (I computed this exactly). You can be smarter and enumerate only genuine spanning trees. Cayley’s formula says a complete graph on n labeled nodes has n^(n−2) of them, which is 20¹⁸, about 2.6 × 10²³. At a billion trees per second that is roughly 8 million years of waiting.

Two tempting shortcuts also fail. “Always take the globally cheapest remaining edge” can close a cycle, and you then need extra machinery to avoid that (this is Kruskal’s idea, and it does need that machinery). “Walk to the nearest unvisited node” builds a path, not a minimum tree. You need a rule that is cheap to apply and provably never makes a mistake.

Phase 2: The Pattern

What single rule lets you build the optimal network without ever looking back?

Picture an archipelago. You own one island and want to connect all the others by bridges at minimum total cost. Prim’s rule is simple: look at every bridge that would connect your connected territory to an island you don’t own yet, build the cheapest one, and repeat. The territory only ever grows, and you never tear a bridge down.

Why is that safe? Split the nodes into two groups: the ones already in your tree and everyone else. The cut property says that the lightest edge crossing any such split belongs to some minimum spanning tree. If that edge is strictly lighter than every other crossing edge, it belongs to every MST. Prim’s algorithm applies this property at every step, with the “tree so far versus the rest” as the split, and Eppstein’s lecture notes describe exactly this reliance on the cut property.

A short exchange argument backs it up. Suppose Prim’s first non-MST choice is edge e. Any real MST must reach across that same split somewhere using an edge f, and f was available when Prim picked e, so e is no heavier than f. Swap f out for e and you still have an MST that agrees with Prim’s tree on one more edge. Repeat and Prim’s tree is an MST.

When to recognize it

Reach for an MST when a problem statement says things like:

  • “connect all nodes / cities / points with minimum total cost”
  • “minimum cable, pipe, road or wire length so everything is connected”
  • “every node reachable with no redundant connections” (a tree, not a graph with cycles)
  • “the cheapest set of edges that keeps the graph connected”
  • “minimize the largest edge on the path between two nodes” (a bottleneck variant, covered in Phase 5)

Prim’s algorithm versus Dijkstra’s

Prim and Dijkstra share a skeleton, a priority queue that repeatedly pops the closest-looking vertex. History explains the overlap: Vojtěch Jarník published the algorithm in 1930, Prim rediscovered it in 1957, and Dijkstra again in 1959, which is why you’ll see it called Jarník’s, Prim–Dijkstra or DJP.

The difference is the key. Dijkstra ranks a vertex by its total distance from the source. Prim ranks a vertex by the weight of the single edge that links it to the tree. That changes what you get back.

Here is a three-node example. Edges are A–B = 1, B–C = 1 and A–C = 1.5. The MST is A–B plus B–C, total weight 2. The shortest path from A to C is the direct edge at 1.5, but inside the MST the A-to-C route costs 2. An MST minimizes the total cost of the network, not the cost between any specific pair. If you’ve read our Dijkstra implementation guide, keep that contrast in mind: same machinery, different objective.

Prim's Algorithm for Minimum Spanning Tree: Full Guide

Phase 3: Step-by-Step Walkthrough

What does the algorithm actually do on a small graph, move by move?

Use this five-node graph (my own example). The edges are A–B 2, A–C 3, B–C 1, B–D 4, C–D 5, C–E 6 and D–E 7. The heap holds entries of the form (weight, vertex), and I’ll note which tree vertex each entry came from. Start at A. The starting vertex is arbitrary: it changes the order of steps but not the final tree’s weight.

StepPop (weight, vertex) viaWhat happensPushed onto heapTree edgesTotal
1(0, A) startAdd A(2,B) (3,C)none0
2(2, B) via AAdd B(1,C) (4,D)A–B2
3(1, C) via BAdd C(5,D) (6,E)A–B, B–C3
4(3, C) via AStale, skipnothingunchanged3
5(4, D) via BAdd D(7,E)A–B, B–C, B–D7
6(5, D) via CStale, skipnothingunchanged7
7(6, E) via CAdd EnothingA–B, B–C, B–D, C–E13
8(7, E) via DStale, skipnothingunchanged13
Prim's Algorithm for Minimum Spanning Tree: Full Guide

The MST has weight 13: A–B (2), B–C (1), B–D (4) and C–E (6). I confirmed that total with the code in Phase 4.

Look at step 4. When B joined at step 2, it offered C a link costing 1, which beats the 3 that A had offered at step 1. The old (3, C) entry is still sitting in the heap, but C is already in the tree by the time it surfaces. A standard binary heap can’t cheaply update an entry in place, so the usual trick is lazy deletion: push duplicates freely and discard outdated ones when they pop.

What most tutorials get wrong

Many explainers say “mark the vertex visited and push its edges” without saying when to mark. The correct moment is when the vertex is popped, because only then do you know no cheaper link can still arrive. Marking at push time feels equivalent and is wrong.

Run the example above with mark-on-push. Vertex C is marked the instant A pushes (3, C), so B’s cheaper offer of (1, C) is never queued. I ran that variant and it returns 15 instead of 13. It builds a valid spanning tree, which is why the bug survives casual testing, but not a minimum one. Always mark on pop.

Phase 4: Code Templates

Here are three templates you can reuse. All Python needs is version 3.9 or newer and the standard library. The C++ compiles with g++ -std=c++17. I tested them rather than eyeballing them: the Python heap version matched Kruskal’s algorithm on 3,000 random graphs (with negative weights, self-loops, parallel edges, and disconnected graphs included), matched a full brute-force search over all spanning trees on 300 tiny graphs, the dense version matched the heap version on 300 random point sets, and the C++ matched the Python on 200 random graphs.

Python: heap version for edge lists

import heapq
from typing import List, Tuple

Edge = Tuple[int, int, int]  # (u, v, weight)


def prim_mst(n: int, edges: List[Edge]) -> Tuple[int, List[Edge]]:
    """Heap-based Prim (lazy deletion). Vertices are 0..n-1.

    Returns (total_weight, chosen_edges). Raises ValueError if the graph
    is disconnected, because no spanning tree exists.
    Time O(E log E) = O(E log V); space O(V + E).
    """
    if n == 0:
        return 0, []
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((w, v))
        adj[v].append((w, u))

    in_tree = [False] * n
    heap = [(0, 0, -1)]            # (edge weight, vertex, parent); start at vertex 0
    total, chosen = 0, []

    while heap:
        w, u, parent = heapq.heappop(heap)
        if in_tree[u]:             # stale entry: u joined the tree via a cheaper edge
            continue
        in_tree[u] = True          # mark on POP, not on push
        total += w
        if parent != -1:
            chosen.append((parent, u, w))
        for w2, v in adj[u]:
            if not in_tree[v]:
                heapq.heappush(heap, (w2, v, u))

    if len(chosen) != n - 1:
        raise ValueError("graph is disconnected: no spanning tree exists")
    return total, chosen

Calling it on the Phase 3 graph, with A to E mapped to 0 to 4, looks like this:

edges = [(0,1,2), (0,2,3), (1,2,1), (1,3,4), (2,3,5), (2,4,6), (3,4,7)]
print(prim_mst(5, edges))   # (13, [(0, 1, 2), (1, 2, 1), (1, 3, 4), (2, 4, 6)])

What problem it solves: It computes the MST weight and the actual edges for a graph given as an edge list, and tells you loudly when no spanning tree exists.

Key parts: The heap stores (weight, vertex, parent) so you can recover the edge when a vertex is accepted. The in_tree check on pop implements lazy deletion. The final length check catches disconnected input, which would otherwise silently return a partial tree.

Production notes: Each edge can be pushed at most twice, once from each endpoint, so the heap never exceeds 2E entries and the total cost is O(E log E). Since E is at most V², log E is at most 2 log V, so this equals O(E log V). Memory is O(V + E). The failure modes are easy to hit: forgetting the connectivity check, and building a V² edge list for a point set that you could have handled with the dense version below.

Python: dense version for points (no edge list)

def prim_dense(points: List[List[int]]) -> int:
    """Array-based Prim for a complete graph given as 2-D points (Manhattan cost).
    No edge list is ever built. Time O(V^2); space O(V)."""
    n = len(points)
    INF = float("inf")
    best = [INF] * n               # cheapest known link from each vertex to the tree
    in_tree = [False] * n
    best[0] = 0
    total = 0
    for _ in range(n):
        u = -1
        for i in range(n):         # linear scan replaces the heap
            if not in_tree[i] and (u == -1 or best[i] < best[u]):
                u = i
        in_tree[u] = True
        total += best[u]
        ux, uy = points[u]
        for v in range(n):
            if not in_tree[v]:
                d = abs(ux - points[v][0]) + abs(uy - points[v][1])
                if d < best[v]:
                    best[v] = d
    return total

A quick check: four points [[0,0],[3,4],[6,0],[3,0]] give 10, from links of 3, 3 and 4.

What problem it solves: When every pair of points is a candidate edge, the graph is complete and implicit. This version never materializes it.

Key parts: best[v] is the cheapest link from v to the current tree, updated whenever a new vertex joins. The inner linear scan finds the next vertex in O(V), replacing the heap.

Production notes: Time is O(V²) and space is O(V), versus O(V²) memory just to hold the edge list. On 1,000 random points my run finished in about 0.2 seconds in pure Python. This is the right tool when E is close to V². It is the wrong one for a sparse graph with 10⁵ nodes, where V² is far worse than E log V.

C++: heap version

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

// Heap-based Prim with lazy deletion. adj[u] holds (neighbor, weight).
// Returns the MST weight, or -1 if the graph is disconnected.
// Time O(E log V), space O(V + E).
ll primMST(int n, const vector<vector<pair<int, int>>>& adj) {
    if (n == 0) return 0;
    vector<bool> inTree(n, false);
    using State = pair<ll, int>;                       // (edge weight, vertex)
    priority_queue<State, vector<State>, greater<State>> pq;
    pq.push({0, 0});
    ll total = 0;
    int used = 0;
    while (!pq.empty()) {
        auto [w, u] = pq.top();
        pq.pop();
        if (inTree[u]) continue;                       // stale entry
        inTree[u] = true;                              // mark on pop
        total += w;
        ++used;
        for (auto [v, wt] : adj[u])
            if (!inTree[v]) pq.push({wt, v});
    }
    return used == n ? total : -1;
}

int main() {
    int n, m;
    if (!(cin >> n >> m)) return 1;
    vector<vector<pair<int, int>>> adj(n);
    for (int i = 0; i < m; ++i) {
        int u, v, w;
        cin >> u >> v >> w;
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }
    cout << primMST(n, adj) << "\n";
}

What problem it solves: The same MST computation for competitive-programming style input, with a sentinel return value instead of an exception.

Key parts: greater<State> turns the default max-heap into a min-heap. The total is a long long so large weights can’t overflow a 32-bit int. Structured bindings need C++17.

Production notes: The complexity is identical to the Python heap version. The constant factor is far better, and the -1 sentinel only works when real MST weights can’t be negative. If your weights can be negative, return a separate success flag instead.

Complexity at a glance

ImplementationTimeBest when
Array, linear scan for the minimumO(V²)Dense or implicit graphs (E near V²)
Binary heap, adjacency listO(E log V)Sparse graphs, the default
Fibonacci heap, adjacency listO(E + V log V)Asymptotically best for dense graphs; rarely worth the complexity in practice (my inference)

Wikipedia’s treatment notes that a d-ary heap reaches linear time on sufficiently dense graphs more simply than a Fibonacci heap does. For a refresher on how to read these bounds, see our complete guide to time and space complexity.

Prim versus Kruskal

Both are greedy and both are correct. Kruskal sorts all edges and adds each one unless it closes a cycle, using union-find to detect that. Prim grows a single tree and never needs cycle detection. The sources I checked put both at O(E log V) with a binary heap or a sort.

Prim wins when the graph is dense or implicit, as with the points above. Kruskal wins when you already have an edge list, because it needs only a sort and union-find, and it produces a spanning forest automatically on a disconnected graph. Prim needs an extra step for that, covered next. If you’ve written A* before, note that the loop here has the same shape, a priority queue ordering candidates, as in our A* implementation in C, but with a different priority function.

Phase 5: Variations

Which small changes to the template cover the problems you’ll actually see?

1. Dense, implicit graphs. If the statement gives you coordinates and a distance rule, use prim_dense. Sample task: given the points above, return the minimum total Manhattan length of wire that connects them all. No edge list, O(V²) time.

2. Maximum spanning tree. Flip the objective by negating weights, or by using a max-heap. Sample task: choose the set of links that connects every server with the highest total bandwidth. The cut property works symmetrically, with the heaviest crossing edge instead of the lightest.

3. Minimum spanning forest. The basic algorithm only handles connected graphs. For a disconnected graph, run it from every vertex not yet visited, which yields one tree per component. Sample task: a road map with two separate islands, report the cheapest road network on each. This is the case where the connectivity check from Phase 4 becomes a loop instead of an error.

4. Clustering by cutting the tree. Build the full MST, then delete its k−1 heaviest edges. What remains is k connected groups, which is the standard way to get single-linkage clusters. Sample task: split 100 points into 3 groups where the closest points across groups are as far apart as possible. Don’t try to stop Prim early to get this: stopping early gives you one smaller tree, not k groups.

5. Bottleneck paths. Some problems ask you to minimize the largest edge on a path between two nodes. A standard result says an MST contains such a minimum-bottleneck path for every pair of nodes, so you can build the MST and read off the largest edge on the tree path. Sample task: a hiker wants the route between two points whose steepest single step is as small as possible.

Phase 6: Practice Problems

Work through these in order. Three of them, marked premium, require a LeetCode subscription (1135 and 1168 are confirmed premium in my sources; 261 is from memory).

#ProblemDifficultyHint
11971. Find if Path Exists in Graph*EasyWarm up on connectivity: DFS, BFS or union-find before you add weights.
2261. Graph Valid Tree (premium)*MediumA tree on n nodes is connected with exactly n−1 edges.
3684. Redundant Connection*MediumThe edge that closes the first cycle is the cycle property in action.
41319. Number of Operations to Make Network Connected*MediumCount components and spare edges.
51135. Connecting Cities With Minimum Cost (premium)MediumA direct MST. Return −1 if the graph is disconnected.
61584. Min Cost to Connect All PointsMedium*Complete graph on points, so use the dense variant at O(n²).
71631. Path With Minimum EffortMediumA bottleneck path: the MST connection from Phase 5.
8778. Swim in Rising Water*HardSame minimize-the-maximum idea on a grid.
91168. Optimize Water Distribution in a Village (premium)HardAdd a virtual node for wells, then run a standard MST.
101489. Find Critical and Pseudo-Critical Edges in Minimum Spanning TreeHardForce an edge in, then force it out, and compare MST weights.
111579. Remove Max Number of Edges to Keep Graph Fully TraversableHardEdges come in types, so process the shared type first with union-find.

Problems 1584, 1135, 1168, 1489, 1579 and 1631 all appear on a curated MST problem list that labels the algorithm each one uses. That list tags 1135 and 1631 as Prim, 1489 and 1579 as Kruskal, and 1584 and 1168 as either.

Phase 7: Common Mistakes and Edge Cases

What breaks in practice, and how do you guard against each failure?

  • Marking visited on push. Covered in Phase 3: it returns a valid but non-minimum tree (15 versus 13 on the worked example). Mark on pop.
  • Ignoring disconnected input. Without a check, the loop ends quietly and you return the weight of a partial tree. Compare the number of accepted edges to V−1.
  • Directed graphs. The MST problem is for undirected graphs. The directed analogue, a minimum-cost arborescence, needs a different algorithm (Chu–Liu/Edmonds, which I mention from background knowledge rather than my research sources).
  • Negative weights. Unlike Dijkstra, Prim doesn’t care. My random tests included negative edges and matched Kruskal every time, because the cut property doesn’t depend on the sign of weights.
  • Ties and non-unique MSTs. If all weights are distinct the MST is unique. With ties there can be several MSTs, but they share the same multiset of edge weights, so the total is always the same. Don’t write a test that expects one particular edge set.
  • Overflow. In C++, accumulate the total in long long. A graph with a million edges of weight 10⁹ overflows a 32-bit int long before it finishes.
  • Tiny inputs. Handle n = 0 (total 0) and n = 1 (total 0, no edges). Self-loops are skipped naturally because the endpoint is already in the tree, and parallel edges are resolved because the lighter one pops first.
  • Building V² edges for points. For a few thousand points the edge list alone can dominate memory. Switch to the dense variant.

Phase 8: Where This Appears in Real Systems

Where does anyone actually pay for a minimum spanning tree?

The original motivation was physical wiring. Prim’s 1957 paper was about leasing telephone lines to link geographically distant offices using as little cable as possible, which is the opening scenario of this post. The same shape shows up in transportation, water supply and electrical grid layout, and electrical grids were the original motivation for MSTs in general.

MSTs are also a subroutine inside other algorithms. The Christofides algorithm for approximating the traveling salesman problem starts from one, and MSTs appear in approximating some minimum-cut and matching problems. In data work, single-linkage hierarchical clustering is an MST computation, and so are some approaches to image segmentation and gene-expression analysis.

I’m not going to claim that a specific company’s product uses Prim’s algorithm, because none of the sources I read document that, and internals like these are usually not public. What the sources do support is the algorithm family and the problem classes above.

One engineering inference worth flagging, which is mine and not from a source: for large embedding sets you usually can’t afford the full V² graph. A common workaround is to restrict candidate edges to each point’s nearest neighbors, which is exactly what an approximate nearest-neighbor index returns. If you’re curious how those indexes work, our post on vector databases like FAISS, Pinecone, Chroma and Weaviate is a good starting point. The MST you get from a neighbor graph is an approximation, not the exact answer.

Key Takeaways

  • An MST connects every node at minimum total cost using exactly V−1 edges, and brute force over all trees is astronomically slow even at 20 nodes.
  • Prim’s algorithm grows one tree, always adding the cheapest edge that reaches a new vertex, and the cut property proves that choice is safe.
  • Prim ranks vertices by one edge’s weight, Dijkstra by total distance from the source, and an MST does not preserve shortest paths.
  • Use the heap version (O(E log V)) for sparse edge lists and the array version (O(V²)) for dense or implicit graphs like point sets.
  • Mark a vertex visited when you pop it, never when you push it. The wrong choice returns a valid tree that isn’t minimal.
  • Check that you accepted V−1 edges, and run once per component if you want a forest.
  • Negative weights and tied weights are fine for the total, but tied weights mean the edge set may not be unique.

FAQ

What is Prim’s algorithm used for?

It finds a minimum spanning tree: the cheapest set of edges that connects every node of an undirected weighted graph. Typical uses are network and infrastructure layout, subroutines in approximation algorithms such as Christofides for the traveling salesman problem, and clustering.

What is the time complexity of Prim’s algorithm?

It depends on the data structure. A linear scan gives O(V²), a binary heap with an adjacency list gives O(E log V), and a Fibonacci heap gives O(E + V log V). For most interview problems, the binary heap or array version is the right choice.

Is Prim’s algorithm better than Kruskal’s?

Neither is strictly better. Prim suits dense or implicit graphs, like points on a plane, because it never needs the full edge list. Kruskal suits graphs already given as edge lists and handles disconnected graphs directly by producing a forest.

Does Prim’s algorithm work with negative edge weights?

Yes. The cut property doesn’t depend on whether weights are positive, so Prim’s algorithm still finds the minimum spanning tree. This is a key difference from Dijkstra’s algorithm, which fails with negative edges.

What is the difference between Prim’s and Dijkstra’s algorithms?

Both use a priority queue and grow outward from a start vertex. Dijkstra orders vertices by their total distance from the source and returns shortest paths. Prim orders them by the weight of the single edge connecting them to the tree and returns a minimum spanning tree.

Why does my Prim’s implementation return the wrong total?

The most common cause is marking vertices as visited when you push them instead of when you pop them, which locks in a more expensive connection. A second cause is a disconnected graph where you didn’t compare the number of accepted edges to V−1.


×