Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Connect everything cheaply
EXPERIMENT 45 / 66

Grow one cheap connection at a time.

Build a minimum spanning tree through safe cut-crossing edge choices.

BY NAVAN SAMI◷ 9 MIN READSTRETCHALGORITHM

01 Model the idea

A minimum spanning tree connects all vertices of a connected undirected weighted graph with minimum total edge cost and no cycles. It is not a shortest-path tree from a source. Prim’s algorithm grows one connected set, repeatedly choosing the cheapest available edge crossing from that set to an unvisited vertex. Negative edge weights are allowed for this spanning-tree problem.

THE THING THAT MUST STAY TRUE

Chosen edges connect the visited set without a cycle.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
START with one vertex
CHOOSE the cheapest edge crossing to an unvisited vertex
REPEAT until all vertices join

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

prim.py
import heapq
def prim(graph, start):
    queue, visited, chosen, total = [(0, start, None)], set(), [], 0
    while queue:
        weight, node, parent = heapq.heappop(queue)
        if node in visited: continue
        visited.add(node); total += weight
        if parent is not None: chosen.append((parent, node, weight))
        for neighbour, cost in graph[node]:
            if neighbour not in visited: heapq.heappush(queue, (cost, neighbour, node))
    if len(visited) != len(graph): raise ValueError("Graph is disconnected")
    return total, chosen
graph = {"A": [("B", 3), ("C", 1)], "B": [("A", 3), ("C", 2)], "C": [("A", 1), ("B", 2)]}
print(prim(graph, "A")[0])
↳ EXPECTED OUTPUT
3
  1. 1

    The initial zero-cost queue entry introduces the start without an incoming edge. Every later accepted entry adds one vertex and one edge.

  2. 2

    Stale entries to already visited vertices are skipped. Equal-weight ties can produce different valid minimum spanning trees.

  3. 3

    The fixture uses comparable string vertex ids for tuple ties. Arbitrary objects need a deterministic counter tie-breaker. An undirected adjacency model must include reciprocal edges with consistent weights.

04 Count the cost

TIME

O(E log V) for a simple graph with a binary heap

SPACE

O(V + E) including queued edges

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Explain the difference between an MST total and a source-to-vertex shortest-path distance using the triangle weights 1, 2, and 3.

Reveal one possible solution +
one_possible_solution.py
edges = [("A", "C", 1), ("C", "B", 2)]
print("spanning total:", sum(weight for _, _, weight in edges))
print("A to C:", 1)

06 Check your reasoning

QUICK SIGNAL CHECK

What does an MST minimise?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.