mediumGraphHeapGraphs

Minimum Spanning Tree (Prim's)

mediumTime: O(E log V)Space: O(V+E)

Recognize the pattern

build minimum spanning treegrow tree by adding cheapest edgepriority queue of edges

Brute force idea

If you approach Minimum Spanning Tree (Prim's) in the most literal way possible, you get this: 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.

Better approach

The real unlock in Minimum Spanning Tree (Prim's) comes when you notice this: 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.

Key invariant

The compass for Minimum Spanning Tree (Prim's) is this: 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.

Watch out for

One easy way to drift off course in Minimum Spanning Tree (Prim's) is this: 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.

Graphs Pattern