Prim's Algorithm

Other names:
Jarník's algorithm, Prim-Jarník algorithm

In short: Prim's algorithm finds a minimum spanning tree by starting from any node and repeatedly adding the cheapest edge that connects the tree to a node outside it, until every node is in the tree. With a binary heap as the priority queue, it runs in O(E log V) time. A version that scans a plain array instead of using a heap runs in O(V²) time, which is faster for dense graphs.

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:

  1. Pick any node to start. For now, it's the whole tree.
  2. Put every edge leaving the start node into a min-heap, ordered by weight.
  3. 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.
  4. 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(graph, start): tree = an empty list mark start as in the tree push (weight, start, v) onto a min-heap for each edge from start while the heap isn't empty and tree has fewer than V - 1 edges: pop the cheapest entry (weight, u, v) if v is already in the tree: skip it # stale entry mark v as in the tree add (u, v, weight) to tree for each edge (v, w, weight2) where w isn't in the tree yet: push (weight2, v, w) onto the heap return tree

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.

import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; // lazy prim's algorithm. nodes are numbered 0 to numNodes - 1, and each // edge is {node1, node2, weight}. returns the tree's edges. public static List<int[]> prim(int numNodes, int[][] edges, int start) { // build an adjacency list: graph.get(node) holds {weight, neighbor} pairs List<List<int[]>> graph = new ArrayList<>(); for (int node = 0; node < numNodes; node++) { graph.add(new ArrayList<>()); } for (int[] edge : edges) { graph.get(edge[0]).add(new int[] {edge[2], edge[1]}); graph.get(edge[1]).add(new int[] {edge[2], edge[0]}); } boolean[] inTree = new boolean[numNodes]; inTree[start] = true; // the heap holds {weight, node in the tree, node outside it} for edges // leaving the tree, so the cheapest one is always on top PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])); for (int[] next : graph.get(start)) { heap.add(new int[] {next[0], start, next[1]}); } List<int[]> tree = new ArrayList<>(); while (!heap.isEmpty() && tree.size() < numNodes - 1) { int[] cheapest = heap.poll(); int weight = cheapest[0]; int fromNode = cheapest[1]; int toNode = cheapest[2]; // stale entry: toNode already joined the tree by a cheaper edge if (inTree[toNode]) { continue; } // the cheapest edge leaving the tree: add it and its new node inTree[toNode] = true; tree.add(new int[] {fromNode, toNode, weight}); // edges from the new node to nodes outside the tree are new options for (int[] next : graph.get(toNode)) { if (!inTree[next[1]]) { heap.add(new int[] {next[0], toNode, next[1]}); } } } // fewer than numNodes - 1 edges means the graph isn't connected: // we only reached the nodes in start's connected piece return tree; } public static void main(String[] args) { // shops A through F are nodes 0 through 5 final int A = 0, B = 1, C = 2, D = 3, E = 4, F = 5; int[][] cableCosts = { {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}, }; int total = 0; for (int[] edge : prim(6, cableCosts, A)) { System.out.println("ABCDEF".charAt(edge[0]) + "-" + "ABCDEF".charAt(edge[1]) + " " + edge[2]); total += edge[2]; } System.out.println("Total: " + total); }

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:

import java.util.ArrayList; import java.util.Arrays; import java.util.List; static final int NO_EDGE = Integer.MAX_VALUE; // O(V^2) prim's algorithm for a dense graph. cost[i][j] is the weight of // the edge between nodes i and j, or NO_EDGE if there's no edge. public static List<int[]> primDense(int[][] cost) { int numNodes = cost.length; boolean[] inTree = new boolean[numNodes]; int[] cheapest = new int[numNodes]; // cheapest known edge from the tree to each node int[] cheapestFrom = new int[numNodes]; // the tree node at the other end of that edge Arrays.fill(cheapest, NO_EDGE); Arrays.fill(cheapestFrom, -1); cheapest[0] = 0; // start the tree at node 0 List<int[]> tree = new ArrayList<>(); for (int step = 0; step < numNodes; step++) { // scan for the closest node that isn't in the tree yet: O(V) int node = -1; for (int candidate = 0; candidate < numNodes; candidate++) { if (!inTree[candidate] && (node == -1 || cheapest[candidate] < cheapest[node])) { node = candidate; } } if (cheapest[node] == NO_EDGE) { break; // no edge reaches the remaining nodes: the graph isn't connected } inTree[node] = true; if (cheapestFrom[node] != -1) { tree.add(new int[] {cheapestFrom[node], node, cheapest[node]}); } // the new tree node might offer a cheaper edge to the nodes outside: O(V) for (int neighbor = 0; neighbor < numNodes; neighbor++) { if (!inTree[neighbor] && cost[node][neighbor] < cheapest[neighbor]) { cheapest[neighbor] = cost[node][neighbor]; cheapestFrom[neighbor] = node; } } } return tree; } public static void main(String[] args) { // shops A through F are nodes 0 through 5 final int A = 0, B = 1, C = 2, D = 3, E = 4, F = 5; int[][] cableCosts = { {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}, }; int[][] cost = new int[6][6]; for (int[] row : cost) { Arrays.fill(row, NO_EDGE); } for (int[] edge : cableCosts) { cost[edge[0]][edge[1]] = edge[2]; cost[edge[1]][edge[0]] = edge[2]; } int total = 0; for (int[] edge : primDense(cost)) { System.out.println("ABCDEF".charAt(edge[0]) + "-" + "ABCDEF".charAt(edge[1]) + " " + edge[2]); total += edge[2]; } System.out.println("Total: " + total); }

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.

Frequently Asked Questions

What is Prim's algorithm?

Prim's algorithm finds a minimum spanning tree of a weighted, undirected graph. It starts from any node and repeatedly adds the cheapest edge that connects a node in the tree to a node outside it, until the tree includes every node.

What is the time complexity of Prim's algorithm?

O(E log V) with a binary heap. A version that uses a plain array instead of a heap takes O(V²), which is better for dense graphs, and a Fibonacci heap brings it down to O(E + V log V).

What's the difference between Prim's and Dijkstra's algorithm?

Their code looks almost the same, but Prim's orders nodes by the weight of the single edge connecting them to the tree, while Dijkstra's orders them by their total distance from the start. Prim's builds a minimum spanning tree; Dijkstra's builds a tree of shortest paths from the start.

Which is better, Prim's or Kruskal's algorithm?

Both find a minimum spanning tree in O(E log V) time on sparse graphs. Kruskal's is often simpler when the graph is given as a list of edges, while Prim's fits adjacency lists and, with its O(V²) array version, is faster on dense graphs.

Is Prim's algorithm greedy?

Yes. At every step it takes the cheapest edge leaving the tree and never reconsiders. The cut property of minimum spanning trees guarantees that edge belongs to a minimum spanning tree, so the greedy choice is always safe.

Does it matter which node Prim's algorithm starts from?

No. Any start node gives a minimum spanning tree. Different start nodes can add the edges in a different order, and with tied weights they can end up with different trees, but the total weight is always the same.

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .