Quick reference
Prim's algorithm finds a minimum spanning tree by starting from any node and repeatedly adding the cheapest edge that connects a node in the tree to a node outside it, until the tree reaches every node. A priority queue (a min-heap) keeps the cheapest edge leaving the tree on top.
The steps:
- Pick any node to start. For now, it's the whole tree.
- Put every edge leaving the start node into a min-heap, ordered by weight.
- Pop the cheapest edge. If its far end is already in the tree, throw the edge away. Otherwise, add the edge and its new node to the tree, and push the new node's edges to nodes that aren't in the tree yet.
- Repeat until the tree has V - 1 edges, where V is the number of nodes.
Cost:
- O(E log V) time with a binary heap, where E is the number of edges.
- O(V²) time with a plain array instead of a heap, which is faster for dense graphs.
- O(V + E) space for the adjacency list and the heap.
How Prim's Algorithm Works
A minimum spanning tree (MST) is the cheapest set of edges that connects every node in a graph without any cycles. Prim's algorithm builds one by growing a single tree, one node at a time. At every step, it looks at all the edges that cross from the tree to the rest of the graph and takes the cheapest one.
That makes it a greedy algorithm: it always takes the edge that looks best right now and never goes back on it. For minimum spanning trees, that greedy choice is always safe, so Prim's algorithm always finds an MST, just like Kruskal's algorithm does. (It's named for Robert Prim, who published it in 1957, but Vojtěch Jarník described it first, in 1930, so you'll sometimes see it called Jarník's algorithm.)
The min-heap does the hard part: finding the cheapest edge leaving the tree. There's one wrinkle. When a node joins the tree, any edges in the heap that lead to it go stale, since both of their ends are now in the tree. Digging them out of the heap would be slow, so the simplest version, called lazy Prim's, leaves them there and throws them away when they get popped.
Here's lazy Prim's algorithm in pseudocode:
Prim's Algorithm Example, Step by Step
Say your bakery has six shops, A through F, and you want to connect them all to one network so every shop can see every other shop's orders. Picture the shops in two rows: A, B, and C on top, with D, E, and F underneath them. You can run a cable between some pairs of shops, and each cable run has a different cost, in thousands of dollars:
| Cable run (edge) | Cost (weight) |
|---|---|
| A-B | 4 |
| A-D | 2 |
| A-E | 5 |
| B-C | 7 |
| B-E | 3 |
| C-E | 8 |
| C-F | 1 |
| D-E | 6 |
| E-F | 9 |
We want the cheapest set of cables that connects all six shops. Let's start at A. The tree is just {A}, and the heap holds A's three edges. Each step pops the cheapest edge from the heap:
| Step | Pop | What happens | Tree's nodes | Heap afterward (cheapest first) |
|---|---|---|---|---|
| Start | — | Push A's edges | A | A-D 2, A-B 4, A-E 5 |
| 1 | A-D (2) | D is new: add A-D. Push D-E. | A, D | A-B 4, A-E 5, D-E 6 |
| 2 | A-B (4) | B is new: add A-B. Push B-E and B-C. | A, B, D | B-E 3, A-E 5, D-E 6, B-C 7 |
| 3 | B-E (3) | E is new: add B-E. Push C-E and E-F. | A, B, D, E | A-E 5, D-E 6, B-C 7, C-E 8, E-F 9 |
| 4 | A-E (5) | E is already in the tree: throw it away | A, B, D, E | D-E 6, B-C 7, C-E 8, E-F 9 |
| 5 | D-E (6) | E is already in the tree: throw it away | A, B, D, E | B-C 7, C-E 8, E-F 9 |
| 6 | B-C (7) | C is new: add B-C. Push C-F. | A, B, C, D, E | C-F 1, C-E 8, E-F 9 |
| 7 | C-F (1) | F is new: add C-F. That's 5 edges, so stop. | A, B, C, D, E, F | C-E 8, E-F 9 (never popped) |
The minimum spanning tree is A-D, A-B, B-E, B-C, and C-F, for a total cost of 17 ($17,000).
A few things to notice:
- We only push edges to nodes outside the tree. When E joins in step 3, its edges to A, B, and D aren't pushed, since those shops are already in the tree.
- Stale edges get thrown away. A-E and D-E were pushed before E joined the tree, so by the time they're popped in steps 4 and 5, they'd only close a cycle.
- The edges don't come out in sorted order. B-E (3) is added after A-B (4), and the cheapest edge in the whole graph, C-F (1), is added last. Prim's algorithm can only use an edge once one of its ends is in the tree, and the tree doesn't reach C until step 6.
Kruskal's algorithm finds the very same tree on this graph, but it adds the edges in sorted order: C-F (1), A-D (2), B-E (3), A-B (4), B-C (7). Since every edge here has a different cost, the minimum spanning tree is unique, so any correct algorithm (from any start node) has to land on it.
Prim's Algorithm Code
Here's lazy Prim's algorithm with a min-heap. Nodes are numbered 0 to
V - 1 (shop A is 0, B is 1, and so on), and each edge
is a (node1, node2, weight) triple. Python, Java, and C++ have heaps
built in (heapq, PriorityQueue, and
priority_queue). JavaScript doesn't, so the JavaScript
version includes a small binary heap.
Running it on the bakery graph, starting at A, prints the edges in the order Prim's algorithm adds them, matching the table above:
A-D 2 A-B 4 B-E 3 B-C 7 C-F 1 Total: 17
A few details:
- A node joins the tree when it's popped, not when it's pushed. The first edge we find to a node isn't always the cheapest one (A-E was pushed before the cheaper B-E). See common mistakes below.
- Any start node works. Different start nodes can add the edges in a different order, but they all end up with a minimum spanning tree.
- If the graph isn't connected, the heap runs out before the tree reaches every node, and the function returns fewer than V - 1 edges: a minimum spanning tree of just the start node's connected piece. Check the count if you need to know. (To get a tree for every piece, a minimum spanning forest, start Prim's again from each node that hasn't been reached, or use Kruskal's algorithm, which does that on its own.)
Lazy vs. Eager Prim's: Using Decrease-Key
The lazy version's heap can hold up to E entries, including stale ones. The eager version keeps at most one entry per node outside the tree: the cheapest edge found so far from the tree to that node. When a new tree node offers a cheaper edge to some outside node, the eager version lowers that node's priority in the heap with a decrease-key operation, the same way Dijkstra's algorithm lowers a node's distance.
In the example, when B joins the tree in step 2, the eager version would lower E's entry from 5 (via A-E) to 3 (via B-E), instead of pushing a second entry for E.
Decrease-key needs an indexed priority queue that tracks where
each node sits in the heap. Python's heapq, Java's
PriorityQueue, and C++'s priority_queue don't
support it, so in an interview the lazy version is usually the way to
go. With a binary heap, both versions take
O(E log V) time. The eager version's
advantage is a smaller heap: O(V) entries
instead of O(E).
With a Fibonacci heap, decrease-key takes O(1) amortized time, which brings the eager version down to O(E + V log V). That's mostly of theoretical interest: Fibonacci heaps are complicated, and their overhead usually makes them slower than a binary heap in practice.
Prim's Algorithm for Dense Graphs: The O(V²) Version
When a graph is dense, with close to V^2 edges, the heap stops paying for itself: O(E log V) becomes O(V² log V).
So skip the heap. Keep an array
cheapest holding the cheapest known edge from the tree to
each node. In each of V rounds, scan it for the
cheapest node that isn't in the tree yet
(O(V)), add that node, then check whether
the new node offers a cheaper edge to each node outside the tree
(another O(V)). That's
O(V²) time in total, with no heap at all,
and O(V) extra space.
This is the version to reach for when every pair of nodes can be connected, as in "connect all these points with the least total wire." That graph is complete, with V(V - 1)/2 edges, and you can even compute each edge's cost when you need it instead of storing all of them. Here it is, taking the graph as an adjacency matrix:
On the bakery graph (with "no edge" for shops that can't be wired directly), it starts at A and adds the same edges in the same order as the heap version: A-D, A-B, B-E, B-C, C-F, for a total of 17.
Prim's Algorithm Time Complexity
| Version | Time | Extra space | Good for |
|---|---|---|---|
| Lazy, binary heap | O(E log V) | O(V + E) | Sparse graphs, and interviews |
| Eager, binary heap with decrease-key | O(E log V) | O(V + E), with only O(V) in the heap | Keeping the heap small |
| Eager, Fibonacci heap | O(E + V log V) | O(V + E) | Mostly theory |
| Array, no heap | O(V²) | O(V) beyond the adjacency matrix | Dense graphs |
Why the lazy version is O(E log V): building the adjacency list takes O(V + E) time. After that, each edge gets pushed onto the heap at most once (from whichever end joins the tree first) and popped at most once, so there are O(E) heap operations, each costing O(log E). That's O(E log E) time. A graph without duplicate edges has fewer than V^2 edges, so \log E < 2 \log V, and O(E log E) is the same as O(E log V).
Space: the adjacency list takes O(V + E), and the heap can hold up to O(E) edges at once.
Why Prim's Algorithm Works
At every step, split the nodes into two sides: the ones in the tree, and everyone else. The edge Prim's algorithm adds is the cheapest edge crossing between the two sides.
The cut property of minimum spanning trees says that for any split like that, the cheapest crossing edge belongs to a minimum spanning tree. (Our minimum spanning tree page shows why.) So each edge Prim's algorithm adds keeps it on track: there's still an MST that contains every edge picked so far. After V - 1 steps, the tree reaches every node, and it's a minimum spanning tree.
Prim's vs. Dijkstra's Algorithm
Prim's algorithm and Dijkstra's algorithm look almost the same in code. Both grow outward from a start node, both use a min-heap, and both skip nodes they've already finished. The difference is the number they put in the heap:
- Prim's orders nodes by the weight of the one edge that would connect them to the tree.
- Dijkstra's orders nodes by their total distance from the start: the distance to the tree node, plus the edge's weight.
That one change gives a different tree. Starting from A on the bakery graph:
| Prim's (minimum spanning tree) | Dijkstra's (shortest paths from A) | |
|---|---|---|
| Edges in the tree | A-D, A-B, B-E, B-C, C-F | A-D, A-B, A-E, B-C, C-F |
| Total cost of all the cable | 17 | 19 |
| Cost of the route from A to E | 7 (A-B-E) | 5 (A-E) |
| Minimizes | The total weight of the whole tree | The distance from the start to each node |
Use Prim's algorithm to connect everything as cheaply as possible. Use Dijkstra's algorithm to get from one place to another as cheaply as possible. Mixing them up is one of the most common Prim's bugs: add the tree node's distance into the heap priority, and you've written Dijkstra's.
Want to practice the heap loop these two algorithms share? Our Cake Delivery Route question walks through Dijkstra's algorithm one hint at a time.
Prim's vs. Kruskal's Algorithm
| Prim's algorithm | Kruskal's algorithm | |
|---|---|---|
| How the tree grows | One tree spreads out from a start node | A forest of small trees merges into one |
| Next edge | The cheapest edge from the tree to a node outside it | The cheapest remaining edge anywhere that doesn't close a cycle |
| Data structures | Min-heap and an adjacency list (or just arrays for the O(V²) version) | Sorted edge list and a union-find |
| Time | O(E log V), or O(V²) with an array | O(E log E), the same as O(E log V) |
| Best for | Dense graphs, and graphs stored as adjacency lists or matrices | Sparse graphs, especially when you're given a list of edges |
| Graph isn't connected | Only spans the start node's connected piece | Finds a minimum spanning forest |
| Order on the bakery graph | A-D, A-B, B-E, B-C, C-F (starting at A) | C-F, A-D, B-E, A-B, B-C |
On sparse graphs, the two run in the same big O time, so pick whichever fits the input. If you're handed a list of edges, Kruskal's is usually less code. If you have an adjacency list, or every pair of nodes is connected, Prim's is the natural fit.
Common Mistakes
-
Marking a node as "in the tree" when you push it, instead of when you pop it. The first edge you find to a node isn't always the cheapest. On the bakery graph, marking E when A-E (5) is pushed means the cheaper B-E (3) never gets a chance, and F gets connected by E-F (9) instead of C-F (1). The result costs 27 instead of 17.
-
Not skipping stale heap entries. In the lazy version, a popped edge whose far end is already in the tree has to be thrown away. Otherwise you'd add A-E and D-E in the example, creating cycles.
-
Putting the distance from the start in the heap. That turns Prim's into Dijkstra's, which builds a shortest-path tree, not a minimum spanning tree. The priority is just the edge's weight.
-
Assuming the graph is connected. If it isn't, the heap empties before the tree has V - 1 edges. Check the count before you report an answer.
-
Forgetting the graph is undirected. When you build the adjacency list, add each edge in both directions. (And MSTs only make sense for undirected graphs. Directed graphs need a different algorithm, like Chu-Liu/Edmonds'.)
-
Using the heap version on a complete graph. When every pair of nodes is connected, the O(V²) array version is faster and simpler than O(V² log V) with a heap.
See also:
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake