Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Prim proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)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 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.
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.
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 traceImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 tracePredict 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. |
| 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.
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.
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 NoneImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 NoneChoose 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.
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 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Prim proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Lazy-heap Prim | O(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. |
O(V + E) visited and lazy heap storage; trace output adds O(V) accepted rows.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
chosen = min(candidates, key=lambda row: row[1])[2]chosen = min(candidates, key=lambda row: row[0])[2]Where you will hit this: Grow a Spanning Tree with Prim(opens in a new tab)
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.
total += weightif node not in visited:
total += weightWhere you will hit this: Grow a Spanning Tree with Prim(opens in a new tab)
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.
answer = totalanswer = total if len(visited) == len(adjacency) else NoneWhere you will hit this: Maximum Container Area(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27