Medium interview relevanceRoadmap: Advanced
TimeO(E log V) with a binary heap; O(V²) with an array
SpaceO(V + E)

Why it costs this much

Each edge can enter the heap, and each heap operation costs O(log V).

Code

import heapq
def prim(graph, start):                    # graph[u] = [(v, w), ...] for every vertex
    seen, total = set(), 0
    heap = [(0, start)]
    while heap and len(seen) < len(graph):
        w, u = heapq.heappop(heap)         # O(log E) per pop
        if u in seen:
            continue
        seen.add(u)
        total += w
        for v, wt in graph[u]:             # each edge is pushed at most twice
            if v not in seen:
                heapq.heappush(heap, (wt, v))
    return total

Common pitfalls

It assumes a connected, undirected graph. Skip vertices that are already in the tree when you pop them.

Operation by operation

OperationBestAverageWorstSpace
Prim minimum spanning treeO(E log V)O(E log V)O(E log V)O(V + E) with lazy deletion; O(V) with decrease-key

Prim minimum spanning tree. Binary heap and an adjacency list. With an array and no heap it is O(V²), which can win on dense graphs.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list