Minimum Spanning Trees

Data Structures & Algorithms · Graph Algorithms · Advanced · 25 min

Connect every node at the lowest total cost with two greedy algorithms: Kruskal (sort edges + union-find) and Prim (grow a tree with a heap).

Laying cable between towns: you keep buying the cheapest cable that reaches somewhere new, and refuse any cable that would only make a loop.

The idea in everyday words

A council wants to link 6 villages with roads, and every possible road has a price. It does not need a direct road between every pair, only some way to drive from any village to any other. Any road that closes a loop is wasted money, because the villages it joins were already connected. The cheapest road network that still connects everyone is the minimum spanning tree.

What is a spanning tree?

Take an undirected, weighted, connected graph: nodes, two-way edges, and a cost (weight) on every edge.

  • A spanning tree picks some of the edges so that every node is connected and there are no cycles.
  • With V nodes it always has exactly V - 1 edges. (Fewer cannot connect everyone; more must create a loop.)
  • The minimum spanning tree (MST) is the spanning tree with the smallest total weight.

MST is not shortest paths. Triangle: A–B costs 2, B–C costs 2, A–C costs 3.

Question Answer
Cheapest way to connect all three A–B + B–C = 4 (MST)
Shortest route from A to C A–C directly = 3 (Dijkstra)

The MST minimises the total cost of the network. Dijkstra minimises the cost of one route. Different questions, different algorithms.

Why being greedy is safe: the cut rule

Both algorithms are greedy: they keep taking the cheapest edge that looks useful. Why is that never a mistake?

Cut rule: split the nodes into any two groups. The cheapest edge crossing between the groups belongs to some MST.

Why: any spanning tree must cross between the two groups somewhere. If a tree crossed with a more expensive edge, swap that edge for the cheaper one. Everything stays connected and the total gets smaller (or stays equal). So the cheap crossing edge is always safe.

The mirror image is the cycle rule: the most expensive edge on any cycle is never needed, because the rest of the cycle already connects its two ends.

  • Kruskal uses the cycle rule: an edge that would close a loop is rejected.
  • Prim uses the cut rule: "the tree so far" vs "everything else" is the cut, and it takes the cheapest crossing edge.

Kruskal: sort the edges, skip the loops

  1. Sort all edges from cheapest to most expensive.
  2. Start with every node in its own group.
  3. For each edge (u, v): if u and v are in different groups, take the edge and merge the groups. If they are in the same group, the edge would close a loop: skip it.
  4. Stop when you have V - 1 edges.

"Are u and v in the same group?" is exactly what union-find answers. Two small tricks keep it fast: path halving (point nodes closer to the root while you walk up) and union by size (hang the smaller group under the bigger one). With both, each find is nearly O(1) amortized (amortized = averaged over many operations). With path halving alone it is O(log n) amortized; with neither trick, one find can walk a chain of n nodes.

def kruskal(n, edges):
    parent = list(range(n))
    size = [1] * n                          # group sizes, for union by size
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]   # path halving
            x = parent[x]
        return x
    total, used = 0, []
    for u, v, w in sorted(edges, key=lambda e: e[2]):
        ru, rv = find(u), find(v)
        if ru == rv:
            continue                        # same group: a loop
        if size[ru] < size[rv]:
            ru, rv = rv, ru                 # the bigger group stays on top
        parent[rv] = ru                     # merge the groups
        size[ru] += size[rv]
        total += w
        used.append((u, v, w))
    return total, used

edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4), (3, 4, 2)]
print(kruskal(5, edges))

Cost: sorting is O(E log E), and the union-find work is nearly O(E) in total. So O(E log E) overall.

Prim: grow one tree with a heap

Prim starts from any node and grows a single tree.

  1. Put the start node in the tree and push its edges into a min-heap.
  2. Pop the cheapest edge. If its far end is already in the tree, skip it (it would close a loop).
  3. Otherwise add that node, add the edge's weight, and push the new node's edges to outside nodes.
  4. Stop when all V nodes are in.
import heapq

def prim(n, edges):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((w, v))
        adj[v].append((w, u))
    seen = [False] * n
    heap = [(0, 0)]                 # (cost to attach, node)
    total = 0
    while heap:
        w, v = heapq.heappop(heap)
        if seen[v]:
            continue
        seen[v] = True
        total += w
        for wx, x in adj[v]:
            if not seen[x]:
                heapq.heappush(heap, (wx, x))
    return total if all(seen) else -1

print(prim(5, [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4), (3, 4, 2)]))

It looks almost like Dijkstra. The one difference: Dijkstra's heap key is distance from the start, Prim's key is the weight of the single edge that attaches the node. Cost: O(E log V).

Kruskal or Prim?

Situation Pick Why
You are given a list of edges Kruskal sort + union-find, short to write
Graph is dense or complete (every pair of points can connect) Prim an O(V²) array version beats sorting V² edges
You already have an adjacency list Prim no need to build an edge list
Need to process edges in weight order for other reasons Kruskal e.g. "critical edges", thresholds

Disconnected graph? No spanning tree exists. Kruskal ends with fewer than V - 1 edges (a "minimum spanning forest"); Prim fails to reach every node. Always check and return the "impossible" value the problem asks for.

Equal weights? The total is always the same, but the chosen edges may differ. That is why problems usually ask for the total cost.

Step by step

  1. Sort the edges:

    B–C 1, B–D 2, A–C 3, E–F 3, A–B 4, C–D 4, C–E 5, D–F 6, D–E 7. Every node is its own group.

  2. Take B–C (1) and B–D (2):

    Both join different groups. Groups now: {B, C, D}, {A}, {E}, {F}. Total 3.

  3. Take A–C (3) and E–F (3):

    A joins {B, C, D}; E and F form a pair. Groups: {A, B, C, D}, {E, F}. Total 9.

  4. Reject A–B (4):

    A and B are already in the same group (path A → C → B). Adding A–B would close a loop, so skip it.

  5. Reject C–D (4):

    C and D are already joined through B. Another loop: skip.

  6. Take C–E (5) and stop:

    C–E joins the two remaining groups. That is 5 edges for 6 nodes, so the tree is complete. Total = 14.

Code example

def kruskal(n, edges):
    parent = list(range(n))
    size = [1] * n                          # group sizes, for union by size
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    total, used = 0, []
    for u, v, w in sorted(edges, key=lambda e: e[2]):
        ru, rv = find(u), find(v)
        if ru == rv:
            print("reject", "ABCDEF"[u] + "-" + "ABCDEF"[v], w, "(would close a loop)")
            continue
        if size[ru] < size[rv]:
            ru, rv = rv, ru                 # the bigger group stays on top
        parent[rv] = ru
        size[ru] += size[rv]
        total += w
        used.append("ABCDEF"[u] + "-" + "ABCDEF"[v])
        print("accept", used[-1], w, "total =", total)
        if len(used) == n - 1:
            break
    return total

edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4),
         (2, 4, 5), (3, 4, 7), (3, 5, 6), (4, 5, 3)]
print("MST weight:", kruskal(6, edges))

Complexity

  • Time: O(E log E) for Kruskal (sorting dominates; union-find with path halving and union by size is nearly O(1) amortized per edge, or O(log n) amortized with path halving alone). Prim with a heap is O(E log V).
  • Space: O(V + E): the edge list or adjacency list, plus the union-find parent array or the heap

Interview tips

  • Clarify first: undirected? connected? Are weights allowed to be negative? (MST algorithms handle negative weights fine, unlike Dijkstra.)

  • Name the cut rule when asked why greedy works: the cheapest edge across any split is always safe.

  • For "Min Cost to Connect All Points", say the graph is complete (about n²/2 edges) and that Prim avoids sorting them all.

  • Know union-find cold: find with path compression, union by size or rank, and "same root means same group".

Challenge: Cheapest Network

You are given n nodes (0 to n - 1) and a list of undirected edges [u, v, w] where w is the cost of building that link.

Return the minimum total cost to connect all nodes. If it is impossible to connect them all, return -1.

One test is a huge star (node 0 linked to everyone). A union-find with no tricks turns into one long chain there and is too slow. Path halving (or compression) or union by size alone is enough to pass it, but use both: together they make each find nearly O(1) amortized.

Example: mst_cost(4, [[0, 1, 1], [1, 2, 2], [2, 3, 3], [0, 3, 4], [0, 2, 5]]) → 6

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Graph Algorithms

Previous: Shortest Paths (Dijkstra) · Next: Greedy & Intervals