GeeksforGeeks Medium

MST — Prim's Algorithm

MST — Prim's Algorithm is a GFG problem (Medium). You get a connected, undirected, weighted graph with V vertices and a list edges, where [u, v, w] is an edge between u and v of weight w.

  • Return the total weight of a minimum spanning tree: a set of V − 1 edges that connects every vertex with the smallest possible sum of weights.
  • Only the sum is asked for, not the edges themselves.

A dense graph with 1,000 vertices can have about 500,000 edges, so the work should be close to linear in E.

Constraints
  • 2 <= V <= 1000
  • V - 1 <= E <= V * (V - 1) / 2
  • 1 <= w <= 1000
  • The graph is connected and has no self-loops or repeated edges.
graphmstgreedyheap
Open on GeeksforGeeks ↗
02

Intuition

Prim's algorithm grows one tree. Start with vertex 0 on its own. Any edge with exactly one end in the tree is a candidate. Take the cheapest candidate, pull its outside end into the tree, and repeat until all V vertices are in.

Why is the cheapest candidate e always safe? Take a minimum spanning tree that does not use e. Adding e to it closes a cycle, and that cycle has to cross from the tree side to the outside at least once more, through some edge f. Since e was the cheapest crossing edge, f weighs at least as much. Swapping f out for e keeps every vertex connected and does not raise the total, so some minimum spanning tree contains e. This is the cut property.

A min-heap keeps the candidates, so the cheapest is always on top.

How to spot this pattern

"Connect every vertex at the lowest total cost" is a minimum spanning tree. Reach for Prim's algorithm when the graph comes as an adjacency list or a dense matrix, and for Kruskal's when you have a plain edge list and union-find at hand.

03

Approach

Try it first

Before reading on, decide what the min-heap should hold, and when a vertex counts as part of the tree: when its entry is pushed, or when it is popped. Then check your rule on a vertex that is first reached by an expensive edge and later by a cheap one.

1

Store each edge in both directions

For every [u, v, w], add (w, v) to adj[u] and (w, u) to adj[v]. The input lists each edge once, but the tree may reach it from either end.

2

Start the heap with vertex 0 at cost 0

Push (0, 0). Every vertex ends up in the tree, so any start gives the same total, and the zero cost means the first vertex adds nothing.

3

Pop the cheapest entry and skip it if stale

The heap can hold several entries for one vertex, pushed from different tree vertices. The first one popped is its cheapest link to the tree. A later entry for a vertex already in the tree is stale: using it would close a cycle, so drop it.

4

Take the vertex and add its weight

Mark the popped vertex as in the tree and add the entry's weight to total. By the cut property that weight belongs to a minimum spanning tree, so it is never taken back.

5

Push the edges that now cross out of the tree

For each neighbour v of the new vertex that is not yet in the tree, push (w, v). Neighbours already inside are skipped, since that edge joins two tree vertices.

6

Return the total when the heap is empty

The graph is connected, so by then all V vertices have been taken once each and total is the weight of a minimum spanning tree.

04

Code in Python, C++ and Java

▶1import heapq
▶2 
▶3class Solution:
▶4 def spanningTree(self, V, edges):
▶5 adj = [[] for _ in range(V)]
▶6 for u, v, w in edges:
▶7 adj[u].append((w, v))
▶8 adj[v].append((w, u))
▶9 
▶10 in_tree = [False] * V
▶11 heap = [(0, 0)]
▶12 total = 0
▶13 while heap:
▶14 w, u = heapq.heappop(heap)
▶15 if in_tree[u]:
▶16 continue
▶17 in_tree[u] = True
▶18 total += w
▶19 for w2, v in adj[u]:
▶20 if not in_tree[v]:
▶21 heapq.heappush(heap, (w2, v))
▶22 return total
531012min-heap: cost, vertex0to 0toptotal0start: vertex 0 at cost 0
heap(0, 0)cost, vertex
total0
Every edge is stored at both of its ends. The tree starts empty and the heap holds one entry: vertex 0 at cost 0. Any start would do, since every vertex must end up in the tree.
531012min-heap: cost, vertexemptytotal0=0take vertex 0 for 0 → total 0
vertex0joins the tree
total0
Pop vertex 0. It is the whole tree for now, and it cost nothing to add.
531012min-heap: cost, vertex5to 1toptotal0=0edge 0 to 1 costs 5 → push it
neighbour1outside the tree
heap1 entries
Vertex 1 is still outside, so the edge of weight 5 now crosses out of the tree. Push it; the heap keeps the cheapest crossing edge on top.
531012min-heap: cost, vertex1to 25to 1toptotal0=0edge 0 to 2 costs 1 → push it
neighbour2outside the tree
heap2 entries
Vertex 2 is still outside, so the edge of weight 1 now crosses out of the tree. Push it; the heap keeps the cheapest crossing edge on top.
531012min-heap: cost, vertex5to 1toptotal0+1=1take vertex 2 for 1 → total 1
vertex2joins the tree
total1
The top of the heap is the cheapest edge leaving the tree, 1 to vertex 2. By the cut property some minimum spanning tree uses it, so take it: 2 joins the tree and the total becomes 1.
531012min-heap: cost, vertex3to 15to 1toptotal0+1=1edge 2 to 1 costs 3 → push it
neighbour1outside the tree
heap2 entries
Vertex 1 is still outside, so the edge of weight 3 now crosses out of the tree. Push it; the heap keeps the cheapest crossing edge on top. Vertex 1 already has an entry; the cheaper one will be popped first and the other becomes stale.
531012min-heap: cost, vertex3to 15to 1toptotal0+1=1vertex 0 is in the tree → skip that edge
neighbour0already inside
heap2 entriesno change
The edge from 2 to 0 leads back into the tree, so it does not cross out of it. Only a crossing edge can bring in a new vertex, so this one is not pushed.
531012min-heap: cost, vertex5to 1toptotal0+1+3=4take vertex 1 for 3 → total 4
vertex1joins the tree
total4
The top of the heap is the cheapest edge leaving the tree, 3 to vertex 1. By the cut property some minimum spanning tree uses it, so take it: 1 joins the tree and the total becomes 4.
531012min-heap: cost, vertex5to 1toptotal0+1+3=4vertex 0 is in the tree → skip that edge
neighbour0already inside
heap1 entriesno change
The edge from 1 to 0 leads back into the tree, so it does not cross out of it. Only a crossing edge can bring in a new vertex, so this one is not pushed.
531012min-heap: cost, vertex5to 1toptotal0+1+3=4vertex 2 is in the tree → skip that edge
neighbour2already inside
heap1 entriesno change
The edge from 1 to 2 leads back into the tree, so it does not cross out of it. Only a crossing edge can bring in a new vertex, so this one is not pushed.
531012min-heap: cost, vertexemptytotal0+1+3=4vertex 1 is already in → drop the 5 entry
popped5 to 1stale
total4unchanged
The cheapest entry left reaches vertex 1, but 1 joined the tree earlier through a cheaper edge. Taking this 5 edge would close a cycle, so the entry is stale: drop it and pop again.
531012min-heap: cost, vertexemptytotal0+1+3=4heap empty → minimum spanning tree weighs 4
answer4
tree edges2V − 1 = 2
The heap is empty and all 3 vertices are in the tree, joined by the 2 green edges. Their weights add up to 4, the answer.
05

Common pitfalls

Marking a vertex as taken when it is pushed

✗ Wrong
w, u = heapq.heappop(heap)
total += w
for w2, v in adj[u]:
    if not seen[v]:
        seen[v] = True
        heapq.heappush(heap, (w2, v))
✓ Right
w, u = heapq.heappop(heap)
if in_tree[u]:
    continue
in_tree[u] = True
total += w

This is the habit from BFS, but here a vertex reached first by an expensive edge may later be reached by a cheap one. For V = 3, edges [[0,1,5],[0,2,1],[2,1,1]], vertex 1 is locked in through the 5 edge and the answer comes out 6 instead of 2.

Ranking the heap by distance from the start

✗ Wrong
heapq.heappush(heap, (w + w2, v))
✓ Right
heapq.heappush(heap, (w2, v))

Adding the path cost so far turns Prim's into Dijkstra's, which builds a shortest-path tree, not a minimum spanning tree. For V = 3, edges [[0,1,2],[1,2,2],[0,2,3]], it takes vertex 2 through the 3 edge, for a total of 5; the minimum is 2 + 2 = 4.

Storing each edge in one direction only

✗ Wrong
for u, v, w in edges:
    adj[u].append((w, v))
✓ Right
for u, v, w in edges:
    adj[u].append((w, v))
    adj[v].append((w, u))

The tree can then only cross an edge from its first-listed end. For the sample V = 3, edges [[0,1,5],[1,2,3],[0,2,1]], vertex 2 cannot offer its 3 edge to vertex 1, so the answer is 6 instead of 4.

06

Edge cases

Equal weights, like a triangle with every edge 1

The heap may pop either of two equal entries, so different runs can pick different trees. Every minimum spanning tree has the same total, so the answer does not change.

07

Complexity

Time
O(E log E)
Space
O(V + E)
The heap version pushes each edge at most twice, once from each end, and each push or pop costs O(log E). Since E is at most V², log E is at most 2 log V, so this is the same as the usual O(E log V). The adjacency list and the heap each hold O(E) entries.
08

MST — Prim's Algorithm FAQ

Prim's vs Kruskal's: which should I use?

Both give a minimum spanning tree of the same weight. Kruskal's sorts all edges and joins components with union-find, which suits a sparse edge list. Prim's grows one tree from a vertex and needs only a heap and a visited array, which suits adjacency lists and dense graphs.

What is the O(V²) version of Prim's algorithm?

Drop the heap. Keep key[v], the cheapest known edge from the tree to v, and on each of the V rounds scan all vertices for the smallest key outside the tree, then lower its neighbours' keys. That costs O(V²) with no log factor, which beats the heap when E is close to V², as with a complete graph.

Does the starting vertex change the answer?

No. The cut property holds for every cut, so starting anywhere still adds only edges that some minimum spanning tree uses, and every minimum spanning tree has the same total.