Problem Statement
Minimum Spanning Tree (Prim's)
Picture a few towns and some roads between them. Each road has a cost to build. You want every town connected, but you want to spend as little money as possible. The cheapest set of roads that still connects everything is called the minimum spanning tree, or MST. "Spanning" means it reaches every town. "Minimum" means the total cost is as small as possible. The way we build it here is Prim's algorithm: start at one town, and keep adding the single cheapest road that reaches a town you have not connected yet, until every town is in.
Signals to notice
Brute force first
Try all possible spanning trees — exponential. The number of spanning trees grows rapidly with vertices. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
The key insight
Prim's algorithm: start from any vertex, use a min-heap of edges from the growing tree to non-tree vertices. Always add the cheapest edge. with a binary heap. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
Trace it on n=4, edges=[[0,1,1],[0,2,4],[1,2,2],[2,3,3]]
init: visited={0}, total=0, heap=[(1,1),(4,2)] (edges from node 0)
pop (1,1): 1 new -> visited={0,1}, total=1; push (2,2). heap=[(2,2),(4,2)]
pop (2,2): 2 new -> visited={0,1,2}, total=3; push (3,3). heap=[(3,3),(4,2)]
pop (3,3): 3 new -> visited={0,1,2,3}, total=6; node 3's only edge goes to visited 2, nothing pushed
|visited|=4=n -> stop. return total=6What must stay true
At each step, the cheapest edge connecting the MST to a non-MST vertex is always safe to add. This greedy choice never leads to a suboptimal tree (cut property). As long as that statement keeps holding, you can trust the steps built on top of it.
Shape of the loop
build adj list (w,v) both directions
visited={0}; heap=edges from 0; total=0
while heap and |visited|<n:
w,v = pop-min(heap)
if v in visited: continue
visited.add(v); total += w
push (w2,u) for u in adj[v] if u not visited
return totalPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Adding edges to already-visited vertices — check if the destination is already in the MST before processing. The heap may contain stale entries. The fix is usually to return to the meaning of each move, not just the steps themselves.