Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Graphs

Grow the Cheapest Tree.

Don't memorize Prim's algorithm — watch the tree grow. A minimum spanning tree connects every vertex for the least total weight. Prim grows one tree outward from a starting vertex: each step it looks at every edge crossing from the tree to the outside and greedily grabs the cheapest, pulling one new vertex in. A min-heap keeps that cheapest edge at your fingertips, and the cut property proves the greedy grab is always safe.

grow from one vertex · cheapest crossing edge · min-heap frontier · cut property
MST

A tree touching every vertex with minimum total weight — exactly V − 1 edges, no cycle.

CROSSING EDGE

An edge with one endpoint in the growing tree and one outside it.

GREEDY GROW

Always add the cheapest crossing edge — the cut property says it is safe.

MIN-HEAP

A priority queue of frontier edges hands you the cheapest in O(log V).

prim.sim — grow the MST from vertex A
Ready

A weighted graph. Start with just A in the tree. Press Step: the blue dashed edges are the current frontier — the cheapest one (amber) gets added, turns green, and pulls in a new vertex.

repeat: add the min-weight edge crossing tree → outside
0
MST weight
1 / 5
Vertices in tree

The cut property does the proving

Why is grabbing the locally cheapest edge safe? Because of the cut property. Split the vertices into two groups — say the tree so far versus everything else. Any spanning tree must cross that divide somewhere. And the cheapest edge crossing it can always be part of a minimum spanning tree: if some MST used a pricier crossing edge instead, you could swap in the cheaper one and get a tree that is no heavier. Prim leans on this every step. Its cut is always the same shape — the vertices already in the tree versus the rest — and it adds the least-weight edge across that cut. One new vertex joins, the cut redraws itself, and you repeat. A min-heap of the frontier edges makes each cheapest lookup O(log V).

01

Start anywhere

Put a single vertex in the tree. Any starting vertex yields a minimum spanning tree.

02

Look at the cut

Consider every edge crossing from the in-tree vertices to the vertices still outside.

03

Add the cheapest

Take the minimum-weight crossing edge; the cut property makes it safe. One new vertex joins.

04

Repeat V − 1 times

A min-heap keyed by edge weight yields each pick in O(log V), for O((V + E) log V) total.

Time
O((V+E) log V)
Space
O(V)
Edges
V − 1
Proof
Cut property

Prim and Kruskal are the two classic MST builders, and both are greedy. Prim grows a single connected tree outward with a heap of frontier edges — a great fit for dense graphs. Kruskal instead sorts all edges once and adds them cheapest-first, using union-find to reject any that would close a cycle — better for sparse graphs. Prim also looks almost identical to Dijkstra: same heap-driven loop, except Dijkstra keys by distance from the source while Prim keys by the single edge into the tree. Learn one and the other two come nearly free.

Check yourself

1 · What does Prim add at each step?

Prim only considers frontier edges — those leaving the current tree — and takes the minimum-weight one, bringing in one new vertex.

2 · Why is the greedy choice guaranteed correct?

For the cut between the tree and the rest, the cheapest crossing edge can always belong to a minimum spanning tree — so adding it never rules out optimality.

3 · How does Prim differ from Kruskal?

Both build a minimum spanning tree. Prim expands one connected tree; Kruskal processes edges globally cheapest-first, skipping cycles with union-find. Same total weight.

The picture: the cut Prim looks at

tree so far: {A, B, C} 37214569ABCDE edges crossing the box: B–D 4 C–D 5 C–E 6 A–E 9 cheapest: B–D 4 A–C 3 is inside the box, so it is no longer a candidate
The page’s five-vertex graph after Prim has taken A–B and B–C. The shaded box is the tree; only edges that cross its border compete. B–D at 4 is the cheapest, so D joins next. Note that A–C at 3 is cheaper than 4 but no longer competes: both its ends are already in the tree.

Worked example, step by step

Use the page’s graph: A–B 2, A–C 3, B–C 1, B–D 4, C–D 5, C–E 6, D–E 7, A–E 9. Prim starts at A with a lazy min-heap: every edge to an unvisited neighbour is pushed, and an edge popped whose far end is already in the tree is discarded. Ties are not an issue here, since all eight weights differ.

PopWeightDecisionJoinsHeap leftTree weight
start at A–take030
A–B2takeB42
B–C1takeC53
A–C3skipalready in tree43
B–D4takeD47
C–D5skipalready in tree37
C–E6takeE213
D–E7skipalready in tree113
A–E9skipalready in tree013

The tree is A–B, B–C, B–D, C–E with total weight 13. Four pops (A–C, C–D, D–E and A–E) were skipped: by the time they surfaced, their far ends were already in the tree, so the lazy heap simply throws them away. The trace also shows why the heap has to hold edges rather than vertices: A–E sat in the heap with weight 9 from the first step and stayed there to the end, while C–E at 6 won it instead. Kruskal gives the same total on this graph, though not always the same edges when weights tie.

Complexity and trade-offs

CaseTimeSpaceWhy
Prim, lazy binary heapO(E log E)O(E)Each edge is pushed at most twice. On a complete graph of 100 vertices (4,950 edges) with random weights, this run pushed 4,951 entries in all.
Prim, heap with decrease-keyO((V+E) log V)O(V)One entry per vertex, updated when a cheaper edge is found.
Prim, plain arrayO(V²)O(V)Scan all vertices for the cheapest each step. Needs no heap and no edge list, so it wins on dense graphs.
Prim, Fibonacci heapO(E + V log V)O(V)Best asymptotics, rarely better in practice.
KruskalO(E log E)O(V) plus the edge listSort once, then union-find. Better when edges arrive as a list.

Pick by density. With E close to V², the array version does about V² simple steps and never builds a heap, and a geometric point set does not even need an edge list, since distances can be computed on demand. With E close to V, a heap or Kruskal’s sort is cheaper. Either way you need a connected graph to get one tree.

Common mistakes

  • No visited check on pop

    Without the check, an edge to a vertex already in the tree is added anyway. On the triangle [[0,1,1],[1,2,2],[0,2,3]] the loop pops 0, 1, 2 and then the stale edge of weight 3, returning 6 instead of 3.

  • Adding each edge in one direction only

    The graph is undirected, so push both u→v and v→u. On [[0,1,5],[2,1,3],[2,0,4]] from vertex 0, one-way adjacency reaches only 2 of the 3 vertices and returns 5. The correct total is 7.

  • Keying the heap like Dijkstra

    Prim keys by the weight of the single edge into the tree. Keying by distance from the start builds a shortest-path tree instead. On a triangle with 0–1 = 3, 1–2 = 3, 0–2 = 4 it takes 0–1 and 0–2 and totals 7, where the minimum is 6.

  • Marking a vertex when it is pushed, not when it is taken

    Marking on push locks in the first edge that mentions a vertex, even if a cheaper one arrives a step later. On [[0,1,5],[0,2,1],[2,1,2]] this returns 6; the correct answer is 3.

  • Not noticing a disconnected graph

    Prim only spans the component of its start. For 3 vertices and the single edge [[0,1,1]] the loop ends normally with weight 1. Count the vertices taken, and report failure if it is below V.

Where this shows up

  • Network design

    Laying cable, pipe or road between sites at least total cost is the textbook MST. Prim is natural when the sites are points and every pair has a cost, since the cost matrix is the graph.

  • Approximating hard tours

    In a graph whose distances obey the triangle inequality, the MST weight is a lower bound on the optimal travelling-salesman tour, and walking the tree gives a tour at most twice as long.

  • Clustering and image grouping

    Remove the heaviest edges of an MST and what is left are clusters. Single-linkage clustering is exactly this.

  • Sibling of Dijkstra

    The loop is Dijkstra’s with a different key. Knowing one gives you the other, and knowing the difference is the most common follow-up question about either.

SOLVE IT YOURSELF

Solve it: the cheapest way to connect everything

Grow one tree outward, always taking the cheapest edge that reaches somewhere new. It looks too greedy to be optimal, and it is provably optimal. Python or TypeScript, running for real in your browser.

YOUR TASK

Implement mst_weight(n, edges): given n vertices and undirected [u, v, w] edges, return the total weight of a minimum spanning tree — or -1 if the graph is disconnected and no spanning tree exists.

HINTS — 6 IDEAS
  1. Keep a priority queue of candidate edges, seeded with vertex 0 at cost 0.
  2. Pop the cheapest. If that vertex is already in the tree, skip it — stale entries are normal and cheaper to discard than to update in place.
  3. Otherwise add it: mark it seen, add its weight, and push all its edges to unseen neighbours.
  4. Count how many vertices you actually absorbed. Fewer than n means the graph was disconnected — that is the -1 case, and it is easy to forget.
  5. Push (weight, vertex) in that order so the queue compares by weight first.
  6. Lazy deletion makes this O(E log E), which is why the seen-check on pop is load-bearing rather than an optimisation.
CPython · WebAssembly

Questions

Prim or Kruskal — which should I use?

Both give a minimum spanning tree. Prim with a heap is O(E log V) and shines on dense graphs (and can be O(V²) with a simple array). Kruskal is O(E log E) dominated by sorting the edges plus near-constant union-find, which suits sparse graphs. Pick by graph density.

Does the MST depend on the start vertex?

No. Prim produces a minimum spanning tree from any starting vertex. If all edge weights are distinct the MST is unique, so the start cannot change it; with tied weights you might get a different edge set but the same total weight.

Why does Prim look so much like Dijkstra?

Both run a heap-driven greedy loop that repeatedly extracts the closest outside vertex. The only difference is the key: Dijkstra uses the total distance from the source, while Prim uses just the weight of the single edge connecting a vertex to the current tree.

One tree, always the cheapest way out.

Start with a vertex, add the least-weight crossing edge, redraw the cut, repeat. The cut property makes every greedy step safe.

Finished this one? 0 / 99 Algorithms done
NextCycles Into Components: Tarjan’s SCC Next on the “What is connected to what” ladder · rung 4 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms