Data Structures · Visualization
Graph: Prim MST
Graph
Prim's algorithm also builds a Minimum Spanning Tree, but instead of sorting all edges globally like Kruskal's, it grows a single connected tree outward one edge at a time, always adding the cheapest edge that connects a new node to the tree so far. Time: O(E log V) with a binary heap priority queue. Space: O(V + E) for the graph and priority queue.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Prim MST
GraphPrim's algorithm also builds a Minimum Spanning Tree, but instead of sorting all edges globally like Kruskal's, it grows a single connected tree outward one edge at a time, always adding the cheapest edge that connects a new node to the tree so far. A priority queue (min-heap) is used to efficiently find that cheapest available edge at each step.
How Prim MST Works
- Start with any single node in the tree, and every edge connected to it as 'available'.
- Repeatedly pick the cheapest available edge that connects a node already in the tree to a node not yet in the tree.
- Add that edge and the new node to the tree.
- Add the newly reachable node's edges to the available options (using a priority queue).
- Repeat until every node has been added to the tree.
Prim MST Worked Example
Input: Start at A; edges A-B(3), A-C(2), B-C(1)
- Tree = {A}. Available edges: A-B(3), A-C(2)
- Pick cheapest: A-C(2). Tree = {A, C}. Add C's edges: B-C(1)
- Available edges now: A-B(3), B-C(1). Pick cheapest: B-C(1). Tree = {A, C, B}
Output: MST edges: A-C, B-C (total weight 3)
Press ▶ Run to watch it step by step.
import heapq
def prim(adj):
start = next(iter(adj))
seen = {start}
pq = [(w, start, nxt) for nxt, w in adj[start]]
heapq.heapify(pq)
mst = []
while pq:
w, a, b = heapq.heappop(pq)
if b in seen:
continue
seen.add(b)
mst.append((a, b, w))
for nxt, w2 in adj[b]:
if nxt not in seen:
heapq.heappush(pq, (w2, b, nxt))
return mst
# example: Prim MST fromBehind 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 MST Time & Space Complexity
When to Use Prim MST
- Building minimum-cost networks when starting from a known central node
- Efficient MST construction on dense graphs (often faster than Kruskal's in this case)
- Infrastructure planning (roads, pipelines, utility grids)
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.