Algorithms · Visualized

Prim's MST

Graph Algorithms

Traverse, order, and find shortest paths and spanning trees on graphs — the machinery behind maps, networks, schedulers and dependency resolvers.

A minimum spanning tree connects all V nodes using V−1 edges of minimum total weight. Time: O(E log V) average, O(E log V) worst; space: O(V + E) for the adjacency list and priority queue.

Big-O: Traversals O(V + E); Dijkstra O(E log V) with a heap; Bellman–Ford O(V·E); Floyd–Warshall O(V³); MST O(E log E).

Prim's Minimum Spanning Tree

Graph Algorithms

A minimum spanning tree connects all V nodes using V−1 edges of minimum total weight. Prim grows one tree from an arbitrary start: at every step it takes the cheapest edge with exactly one endpoint inside the tree, pulling a new node in. Cut optimality guarantees this greedy choice is always safe.

How Prim's MST Works

  1. Start with any node in the tree; every other node is outside.
  2. Look at all edges that cross from inside the tree to outside.
  3. Pick the crossing edge of minimum weight and add it — together with the new endpoint — to the tree.
  4. Repeat until all V nodes are inside; exactly V−1 edges will have been chosen.
  5. A priority queue of frontier edges makes each pick O(log E).

Prim's MST Worked Example

Input: {graph: A—B(4), A—C(2), B—C(1), B—D(5), C—D(8), C—E(10), D—E(2), D—F(6), E—F(3), start: A}

From {A}: cheapest crossing edge A—C(2). From {A,C}: B—C(1) beats A—B(4). From {A,C,B}: B—D(5). From {A,C,B,D}: D—E(2). From {A,C,B,D,E}: E—F(3). Total = 2+1+5+2+3 = 13 — the minimum possible.

Prim's MSTO(E log V)
Grow one tree outward, always adding the cheapest edge that leaves it.
1
0
0
1
0
2
0
3
0
4
0
5
4215810263ABCDEF
tree edges—
weight0
Step 1 / 12
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Start from A. Grow one tree outward, always taking the cheapest edge that leaves it.
Python · Graph Algorithms in Code
import heapq

def prim_mst(n, edges):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((w, v))
        adj[v].append((w, u))
    visited = [False] * n
    total = 0
    pq = [(0, 0)]                          # (weight, node)
    while pq:
        w, u = heapq.heappop(pq)
        if visited[u]:
            continue
        visited[u] = True                  # cheapest crossing edge wins
        total += w
        for wv, v in adj[u]:
            if not visited[v]:
                heapq.heappush(pq, (wv, v))
    return total

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Prim's MST Time & Space Complexity

BestO(E log V)
AverageO(E log V)
WorstO(E log V)
SpaceO(V + E) for the adjacency list and priority queue

When to Use Prim's MST

  • Network cabling: connect offices, power lines or clusters with the least total wire.
  • Approximation building blocks (e.g. the 2-approximation for metric TSP) and cluster analysis.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.