AlgoViz

Prim's algorithm

medium 22 min

A minimum spanning tree connects every vertex of a weighted, undirected graph with the least total edge weight.

See it run

Grow one tree from a start vertex, always adding the cheapest edge that leaves it, until every vertex is in.

Operations

Lazy Prim, step by step

The original app's simple graph: six vertices, nine weighted edges, start at A. A min-heap of (weight, from, to) hands back the cheapest edge leaving the tree.

Step 1 of 12

The graph

431245261ABCDEF

heap (smallest first)

empty

tree edges · total 0

empty

Six vertices and nine edges. A spanning tree keeps all V = 6 vertices connected with exactly V - 1 = 5 edges and no cycle. We want the one with the smallest total weight.

Step 1: The graph

import heapqdef prim(graph, start):    visited = {start}    heap = [(w, start, v) for v, w in graph[start]]    heapq.heapify(heap)    mst, total = [], 0    while heap and len(visited) < len(graph):        w, u, v = heapq.heappop(heap)        if v in visited:            continue                  # stale: v joined the tree earlier        visited.add(v)        mst.append((u, v, w))        total += w        for nxt, wt in graph[v]:            if nxt not in visited:                heapq.heappush(heap, (wt, v, nxt))    return mst, total
Time
O(E log V)
Space
O(E) heap
spanning tree edges
V - 1 = 5

Mark a vertex visited when its edge is popped, never when it is pushed: a later, cheaper edge may still reach it.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Marking visited on push instead of on pop

    critical

    If a vertex is marked when its first edge is pushed, a cheaper edge found later is rejected and the expensive one is kept. In the simple graph, B would join through A-B (4) instead of C-B (1). Mark it when its edge is popped.

    Wrong
    for nxt, wt in graph[v]:    if nxt not in visited:        visited.add(nxt)              # too early        heapq.heappush(heap, (wt, v, nxt))
    Right
    w, u, v = heapq.heappop(heap)if v in visited:    continuevisited.add(v)                        # on pop
  • No stale check after popping

    critical

    Lazy Prim leaves old entries in the heap. Without the visited check a vertex is added twice, the total is too big and the 'tree' contains a cycle.

    Wrong
    w, u, v = heapq.heappop(heap)mst.append((u, v, w))                 # may close a cycle
    Right
    w, u, v = heapq.heappop(heap)if v in visited:    continuemst.append((u, v, w))
  • Weight not first in the heap tuple

    major

    heapq orders tuples by their first field. Pushing (u, v, w) orders edges by vertex name, so Prim picks arbitrary edges and returns a heavier tree.

    Wrong
    heapq.heappush(heap, (v, nxt, wt))
    Right
    heapq.heappush(heap, (wt, v, nxt))
  • Storing an undirected edge one way only

    major

    Prim walks out of whichever end joins first. If B-C is only in graph[B], starting from C can never use it, and the result is wrong or the graph looks disconnected.

    Wrong
    for u, v, w in edges:    graph[u].append((v, w))
    Right
    for u, v, w in edges:    graph[u].append((v, w))    graph[v].append((u, w))
  • Assuming the graph is connected

    major

    On a disconnected graph the heap empties early and Prim returns the MST of the start's component only. Check that every vertex was reached; for a spanning forest, restart Prim from each unvisited vertex.

    Wrong
    mst, total = prim(graph, 0)return total
    Right
    mst, total = prim(graph, 0)return total if len(mst) == len(graph) - 1 else -1
  • Using Prim on a directed graph

    minor

    The cut property needs undirected edges. A directed 'minimum spanning arborescence' needs Chu-Liu/Edmonds' algorithm; running Prim on directed edges can miss cheaper incoming edges.

    Wrong
    graph[u].append((v, w))      # one-way roads, then prim(...)
    Right
    # undirected: add both directions# directed: use Chu-Liu/Edmonds instead

Interview tips

  • How to explain it

    • Prim grows one tree from a start vertex; each step adds the cheapest edge leaving the tree.
    • It is correct by the cut property: the lightest edge crossing any cut is in some MST.
    • A min-heap of (weight, from, to) with a visited check on pop gives O(E log V).
  • Spot it in the wild

    • Connect all points, cities or computers at minimum total cost.
    • Dense input such as all pairs of points: use the O(V²) array version.
    • A 'virtual source' node turns 'build here or connect' problems into an MST.
  • Memory tricks

    • GROW: Grow from one vertex, Reach for the minimum edge, One new vertex at a time, Way to connect all.
    • Prim = Dijkstra's loop with key = edge weight, not distance from the start.
    • Prim grows a tree; Kruskal merges a forest.
  • Watch out

    • Mark visited on pop, and skip stale entries.
    • Push undirected edges both ways.
    • Check you reached all V vertices before reporting a total.