← Back to Algorithms, page 4

algorithms-0073 · Hard senior

Minimum spanning tree: connect all nodes of a weighted undirected graph at the lowest total edge cost, using both Kruskal's and Prim's algorithms.

Kruskal sorts edges by weight and adds each edge that joins two different components, using union-find: O(E log E). Prim grows one tree from a start node, always taking the cheapest edge leaving the tree from a min-heap: O(E log V). Both are correct by the cut property. If the graph is disconnected there is no spanning tree.

Full answer

Problem

Given n nodes and undirected weighted edges (u, v, w), return the minimum total weight of a spanning tree (a set of n - 1 edges connecting all nodes without cycles), or None if the graph is disconnected.

Example: n = 6 with edges (0,1,4), (0,2,3), (1,2,1), (1,3,2), (2,3,4), (3,4,2), (4,5,6) has MST weight 14 using edges of weight 1, 2, 2, 3 and 6.

Constraints: up to 10^4 nodes and 10^5 edges; weights are positive integers.

Brute force

Enumerate every subset of n - 1 edges, keep those that form a tree, and take the cheapest: O(C(E, n-1) * n), exponential.

Optimal approach

Kruskal: sort edges by weight; for each edge, if its endpoints are in different union-find sets, add it and union them; stop after n - 1 edges.

Prim: start at node 0 with a heap of (weight, node). Pop the cheapest entry; if the node is new, add the weight and push all its edges to nodes outside the tree. Stop when all n nodes are in.

Why it works

Cut property: for any split of the nodes into two groups, the cheapest edge crossing the split belongs to some MST. Kruskal's next edge is the cheapest edge between its two components, and Prim's next edge is the cheapest edge leaving the current tree; in both cases that edge is the cheapest across some cut, so adding it keeps the partial solution extendable to an optimal tree. Skipping an edge inside one component avoids cycles.

Complexity

Kruskal: O(E log E) for sorting plus near-constant union-find, O(V + E) space. Prim with a binary heap and lazy deletion: O(E log V) time (log E and log V differ by at most a factor of 2), O(V + E) space. Prim with an array is O(V^2), good for dense graphs.

Code

python
import heapq
import random
from itertools import combinations


def kruskal(n, edges):
    """Sort edges by weight, add each one that joins two different components.
    O(E log E) for the sort plus near-constant union-find. Returns (total, edges) or None."""
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    total, chosen = 0, []
    for w, u, v in sorted((w, u, v) for u, v, w in edges):
        ru, rv = find(u), find(v)
        if ru != rv:
            parent[ru] = rv
            total += w
            chosen.append((u, v, w))
            if len(chosen) == n - 1:
                break
    return (total, chosen) if len(chosen) == n - 1 else None


def prim(n, edges):
    """Grow one tree from node 0 using a heap of crossing edges. O(E log V)."""
    if n == 0:
        return 0
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((w, v))
        adj[v].append((w, u))
    in_tree, total, heap = [False] * n, 0, [(0, 0)]
    added = 0
    while heap and added < n:
        w, u = heapq.heappop(heap)
        if in_tree[u]:
            continue
        in_tree[u] = True
        total += w
        added += 1
        for e in adj[u]:
            if not in_tree[e[1]]:
                heapq.heappush(heap, e)
    return total if added == n else None


def brute(n, edges):
    """Try every subset of n-1 edges that forms a spanning tree."""
    best = None
    for combo in combinations(edges, n - 1):
        parent = list(range(n))

        def find(x):
            while parent[x] != x:
                x = parent[x]
            return x
        ok = True
        for u, v, _ in combo:
            ru, rv = find(u), find(v)
            if ru == rv:
                ok = False
                break
            parent[ru] = rv
        if ok:
            s = sum(w for _, _, w in combo)
            best = s if best is None else min(best, s)
    return best


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4), (3, 4, 2), (4, 5, 6)]
    total, chosen = kruskal(6, edges)
    assert total == prim(6, edges) == 14 and len(chosen) == 5
    assert kruskal(3, [(0, 1, 1)]) is None and prim(3, [(0, 1, 1)]) is None   # disconnected
    assert kruskal(1, []) == (0, []) and prim(1, []) == 0
    rng = random.Random(73)
    for _ in range(300):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(1, 9)) for _ in range(rng.randint(0, 9))]
        k = kruskal(n, es)
        b = brute(n, es) if n > 1 else 0
        assert (k[0] if k else None) == prim(n, es) == b
    print("all tests passed")

Save as b73_mst.py and run python3 b73_mst.py. It prints all tests passed (Python 3.13.5).

Edge cases

Disconnected graph (return None; or compute a minimum spanning forest if asked). A single node (cost 0). Parallel edges and self-loops (self-loops are never chosen). Equal weights (many MSTs may exist with the same total).

Pattern

Greedy with an exchange argument (the cut property). Applications: network cabling, clustering (remove the k - 1 heaviest MST edges to get k clusters), approximation for metric TSP, and "minimum cost to connect all points" with Manhattan distances (Prim's O(V^2) on the complete graph).

python
import heapq
import random
from itertools import combinations


def kruskal(n, edges):
    """Sort edges by weight, add each one that joins two different components.
    O(E log E) for the sort plus near-constant union-find. Returns (total, edges) or None."""
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    total, chosen = 0, []
    for w, u, v in sorted((w, u, v) for u, v, w in edges):
        ru, rv = find(u), find(v)
        if ru != rv:
            parent[ru] = rv
            total += w
            chosen.append((u, v, w))
            if len(chosen) == n - 1:
                break
    return (total, chosen) if len(chosen) == n - 1 else None


def prim(n, edges):
    """Grow one tree from node 0 using a heap of crossing edges. O(E log V)."""
    if n == 0:
        return 0
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((w, v))
        adj[v].append((w, u))
    in_tree, total, heap = [False] * n, 0, [(0, 0)]
    added = 0
    while heap and added < n:
        w, u = heapq.heappop(heap)
        if in_tree[u]:
            continue
        in_tree[u] = True
        total += w
        added += 1
        for e in adj[u]:
            if not in_tree[e[1]]:
                heapq.heappush(heap, e)
    return total if added == n else None


def brute(n, edges):
    """Try every subset of n-1 edges that forms a spanning tree."""
    best = None
    for combo in combinations(edges, n - 1):
        parent = list(range(n))

        def find(x):
            while parent[x] != x:
                x = parent[x]
            return x
        ok = True
        for u, v, _ in combo:
            ru, rv = find(u), find(v)
            if ru == rv:
                ok = False
                break
            parent[ru] = rv
        if ok:
            s = sum(w for _, _, w in combo)
            best = s if best is None else min(best, s)
    return best


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4), (3, 4, 2), (4, 5, 6)]
    total, chosen = kruskal(6, edges)
    assert total == prim(6, edges) == 14 and len(chosen) == 5
    assert kruskal(3, [(0, 1, 1)]) is None and prim(3, [(0, 1, 1)]) is None   # disconnected
    assert kruskal(1, []) == (0, []) and prim(1, []) == 0
    rng = random.Random(73)
    for _ in range(300):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(1, 9)) for _ in range(rng.randint(0, 9))]
        k = kruskal(n, es)
        b = brute(n, es) if n > 1 else 0
        assert (k[0] if k else None) == prim(n, es) == b
    print("all tests passed")

Kruskal with union-find and Prim with a heap; random small graphs are checked against exhaustive search over edge subsets.

Complexity

Time: O(E log E) Kruskal, O(E log V) Prim. Space: O(V + E). Prim with an adjacency matrix and no heap is O(V^2), better for dense graphs.

By level

Fresher: Explains Kruskal with sorting and union-find on a small graph. Knows that a spanning tree has n - 1 edges.

Mid: Implements both algorithms, explains the cut property, and chooses by density. Handles disconnected graphs.

Senior: Discusses MST-based clustering, Boruvka's algorithm for parallel settings, and updates when edges change. Applies Prim's O(V^2) method to implicit complete graphs such as point sets.

Key points

  • Spanning tree has n - 1 edges
  • Cut property justifies both greedy choices
  • Kruskal = sorted edges + union-find
  • Prim = grow one tree with a min-heap
  • Disconnected graphs have no spanning tree

Common mistakes

  • Adding an edge inside one component and creating a cycle
  • Forgetting to check for disconnection
  • Using Dijkstra's distance-from-source instead of the edge weight in Prim
  • Claiming the MST is unique when weights tie

Follow-ups

  • How would you find the second-best MST?
  • How do you cluster points into k groups with an MST?
  • Which algorithm do you pick for a dense graph?

Tips

  • State the cut property
  • Compare the two algorithms by graph density
  • Handle the disconnected case

Evaluation rubric

  • Correct algorithm(s)
  • Correctness argument
  • Correct complexity
  • Handles disconnection