Skip to contentKEEP THE CRAFTTHE SANCTUARY

Prim

Grow one minimum spanning tree by repeatedly taking the cheapest edge leaving its visited set. A lazy heap may contain obsolete edges; skip them before charging cost and verify whole-graph connectivity.

1 practice exercise3 interview problems

Recognize it when Input is a weighted undirected adjacency list and one growth frontier is convenient.

Checking your account…

Prim Code Labs

Grow One Connected Tree

Prim starts from one vertex and grows a connected visited set. At every step it chooses the cheapest edge crossing from the tree to an unvisited vertex.

Push Crossing Edges onto a Heap

Offer crossing edges when a vertex is accepted. The lazy heap may retain edges that later become internal; discard those obsolete entries when they are popped.

Trace Prim Frontier Choices

Reference
import heapq

def prim_trace(adjacency,start):
    heap=[(0,start)];visited=set();total=0;trace=[]
    while heap:
        weight,node=heapq.heappop(heap)
        if node in visited:continue
        visited.add(node);total+=weight;trace.append([node,weight,total])
        for neighbor,cost in adjacency[node]:
            if neighbor not in visited:heapq.heappush(heap,(cost,neighbor))
    return trace
Practice

Implement prim_trace(adjacency,start). Edges are [neighbor,weight]; return [node,weight,total] for accepted heap entries. Require nonempty undirected symmetric adjacency, valid neighbor indices and a valid start.

Public tests

  • Accept the cheapest crossing edge

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Prim Frontier Choices

import heapq

def prim_trace(adjacency,start):
    heap=[(0,start)];visited=set();total=0;trace=[]
    while heap:
        weight,node=heapq.heappop(heap)
        if node in visited:continue
        visited.add(node);total+=weight;trace.append([node,weight,total])
        for neighbor,cost in adjacency[node]:
            if neighbor not in visited:heapq.heappush(heap,(cost,neighbor))
    return trace

Accept a Negative Crossing Edge and Skip the Stale Alternative

Predict this triangle in the existing trace Lab. A negative edge is legal, and the earlier weight-7 offer to vertex 2 remains in the heap after a better connection succeeds.

Step Executed statement State Why
Accept root weight,node=heapq.heappop(heap);visited.add(node);total+=weight;trace.append([node,weight,total]);heapq.heappush(heap,(cost,neighbor)) after root iteration: visited={0}, total=0, offers=(4,1),(7,2) The synthetic root cost is zero; its neighbors form the first cut.
Accept vertex 1 weight,node=heapq.heappop(heap);visited.add(node);total+=weight;trace.append([node,weight,total]);heapq.heappush(heap,(cost,neighbor)) after node 1 iteration: total=4, new offer=(-1,2) Only edge cost matters, so a negative new edge can be the next choice.
Accept vertex 2 weight,node=heapq.heappop(heap);visited.add(node);total+=weight;trace.append([node,weight,total]) visited={0,1,2}, total=3 This edge connects the last vertex without making a cycle.
Discard obsolete offer weight,node=heapq.heappop(heap);continue remaining (7,2) contributes no row or cost Lazy storage is safe because eligibility is checked when removed. The continue executes in the already-visited branch.
Print Output
print(prim_trace([[[1,4],[2,7]], [[0,4],[2,-1]], [[0,7],[1,-1]]], 0)) [[0, 0, 0], [1, 4, 4], [2, -1, 3]]

The trace records accepted vertices, not every heap pop. Prim may choose a different tied edge set from another implementation while preserving the minimum total weight.

Skip Vertices Already in the Tree

A popped edge to an already visited vertex would create a cycle, so skip it. The first accepted heap edge for an unvisited vertex is safe by the cut property.

Compute Prim MST Weight

Reference
import heapq

def prim_weight(adjacency):
    if not adjacency:return 0
    heap=[(0,0)];visited=set();total=0
    while heap:
        weight,node=heapq.heappop(heap)
        if node in visited:continue
        visited.add(node);total+=weight
        for neighbor,cost in adjacency[node]:
            if neighbor not in visited:heapq.heappush(heap,(cost,neighbor))
    return total if len(visited)==len(adjacency) else None
Practice

Implement prim_weight(adjacency). Return MST weight from node zero or None if disconnected. Require undirected symmetric adjacency with valid neighbor indices; empty adjacency returns 0 by this Lab convention.

Public tests

  • Reject a disconnected frontier

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compute Prim MST Weight

import heapq

def prim_weight(adjacency):
    if not adjacency:return 0
    heap=[(0,0)];visited=set();total=0
    while heap:
        weight,node=heapq.heappop(heap)
        if node in visited:continue
        visited.add(node);total+=weight
        for neighbor,cost in adjacency[node]:
            if neighbor not in visited:heapq.heappush(heap,(cost,neighbor))
    return total if len(visited)==len(adjacency) else None

Choose Prim or Kruskal

Choose Prim for adjacency-list graphs and connected growth, especially dense graphs with suitable priority structures. Choose Kruskal when edges are already sorted or sparse and union-find is natural.

Explain It in an Interview

Say: “Visited vertices define a cut. The heap’s cheapest live crossing edge is safe, and an already visited endpoint would create a cycle.” The lazy adjacency-list implementation costs O(V + E log(E + 1)) and can store O(E) heap entries. For a simple connected graph, log E is O(log V).

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Lazy-heap PrimO(V + E log(E + 1))O(V + E log(E + 1))At most edge-proportional offers are popped; parallel edges justify log E rather than an unconditional log V.

Space

O(V + E) visited and lazy heap storage; trace output adds O(V) accepted rows.

Assumptions

  • Zero and negative weights are valid for MSTs.
  • The initial (0,start) entry adds the starting vertex but does not represent a paid graph edge.

Invariants Worth Saying Aloud

  1. Visited vertices and accepted edges form one connected acyclic tree.
  2. Every eligible heap entry offers an edge from that tree to an unvisited vertex.
  3. An obsolete entry is rejected before its weight changes total.

When To Use Or Avoid Prim

Use It When

  • Use lazy Prim when heap entries and adjacency scans give a simple interview implementation.
  • Use an O(V^2) matrix-based variant for a dense graph when avoiding a heap is appropriate.

Choose Another Tool When

  • Use a shortest-path algorithm when the objective is root-to-node distance.
  • Use a forest variant or report failure when the graph is disconnected.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Prioritizing total path cost instead of edge cost

A weight-1 crossing edge can have path cost 9. Prim prefers it over a weight-4 edge even if the latter has path cost 4.

Prevent it: Order candidates by the cost of the added edge.

Avoid

chosen = min(candidates, key=lambda row: row[1])[2]

Use instead

chosen = min(candidates, key=lambda row: row[0])[2]

Charging a stale heap entry

The heap can still contain an edge to a vertex already reached cheaply. Adding its weight before checking visited double-counts that vertex.

Prevent it: Skip visited endpoints before updating total.

Avoid

total += weight

Use instead

if node not in visited:
    total += weight

Mistaking one component for the whole graph

Starting at 0 cannot reach a second isolated vertex. A total of zero says nothing about whole-graph connectivity.

Prevent it: Require len(visited) to equal the number of required vertices.

Avoid

answer = total

Use instead

answer = total if len(visited) == len(adjacency) else None

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.