Module contents
Lesson 20 of 33Core 90 min

Minimum spanning trees

Prove the cut and cycle properties, build minimum spanning trees with Kruskal, Prim and Borůvka, and apply them to clustering and approximation.

After this lesson you can

  • Prove the cut and cycle properties and uniqueness with distinct weights.
  • Implement Kruskal, Prim and Borůvka and choose by density and parallelism.
  • Explain the ideas of the Karger–Klein–Tarjan randomized linear algorithm.
  • Apply minimum spanning trees to single-linkage clustering and metric traveling salesperson approximation.

Before you start

Motivation: the cheapest network

In 1926, a Moravian electricity company asked mathematician Otakar Borůvka to design the cheapest network of lines to electrify the region’s south. His answer, published in Czech that year, is the first known algorithm for what we call a minimum spanning tree: given points and cable costs between each pair, connect all for minimum cost. The problem was rediscovered repeatedly (Jarník in 1930, Kruskal in 1956, Prim in 1957, Dijkstra in 1959) because it arises whenever connections carry costs.

  • Physical networks. Wiring, pipes, roads or fiber links: cost is length and redundant connections are unnecessary.
  • Hierarchical clustering. m12’s single linkage is the minimum spanning tree cut at its longest edges. HDBSCAN uses it on a density-adjusted distance.
  • Probabilistic models. The Chow–Liu tree is the best tree-structured model for discrete variables, obtained as a maximum spanning tree weighted by mutual information.
  • Approximation. The MST lower-bounds the optimal traveling salesperson tour, giving the factor-2 metric traveling salesperson approximation. It also underpins Steiner-tree approximations.
  • Image segmentation and percolation. Merging regions by pixel-edge weight is Kruskal with a stopping rule.

The lesson has three layers. First, the problem and three classical algorithms side by side. Next, why: one cut property justifies all three, and its cycle-property twin explains what can be discarded. Finally, speed, up to Karger, Klein and Tarjan’s randomized expected-linear algorithm, and two applications. We use union-find, the indexed priority queue and exchange arguments from the greedy lesson.

The problem and three solutions

Let G=(V,E)G = (V, E) be a connected undirected graph with nn vertices, mm edges and weight function w:E→Rw : E \to \R.

By tree characterizations, every spanning tree has exactly n−1n - 1 edges. A consequence used repeatedly: weights may be negative without changing the problem, since every candidate sums the same number of terms. If GG is disconnected there is no spanning tree; compute a minimum spanning forest, one MST per connected component.

Trying every candidate is infeasible. Complete graph KnK_n has nn−2n^{n-2} spanning trees (Cayley’s formula), which for n=20n = 20 is 2018≈2.6×102320^{18} \approx 2.6 \times 10^{23}. Yet almost trivial greedy strategies solve it; three work:

  • Kruskal: traverse edges from lightest to heaviest, keeping each that does not close a cycle.
  • Prim: grow one tree from a vertex, always adding its lightest outgoing edge.
  • Borůvka: start with nn fragments and in each phase join every fragment via its lightest outgoing edge, all at once.
InteractiveKruskal, Prim and Borůvka side by side
Kruskal0/13 · weight 0.0
Edges are examined from lightest to heaviest. Each vertex starts alone.
Prim0/13 · weight 0.0
Start at the marked vertex (click another to change root). Dashed lines are edges leaving the tree.
Borůvka0/13 · weight 0.0
Each vertex is a fragment. At each phase, all fragments simultaneously choose their lightest outgoing edge.
  • tree edge (color = fragment)
  • edge currently considered
  • discarded: would close a cycle
tick 0 / 17
14
Graph edges28 (tree: 13)
Minimum tree weight308.0
Kruskal, Prim and Borůvka steps17 · 13 · 2 phases
Same tree for all three?when finished
The same geometric graph (edge weight is length) with three algorithms and a shared clock. Each panel advances one decision per tick: Kruskal examines an edge (orange if accepted, dashed red if rejected, with the red path already joining its endpoints), Prim adds a vertex (the next edge dashed orange), and Borůvka alternates between ‘each fragment chooses’ and ‘merge’. Vertex colors are fragments. All end at the same tree, but Kruskal examines many edges (discarding cycle closers), Prim takes n−1n - 1 sequential steps, and Borůvka only a few phases with many edges at once. Change vertex count and graph, and click a vertex in Prim's panel to change its root.

Run the initial graph (14 vertices, 28 edges) to completion. Kruskal examines 17 edges, rejects 4 and keeps 13; Prim takes 13 steps; Borůvka finishes in 2 phases. All agree edge by edge and the tree weighs 308.0. The same holds for any other figure graph, independently of Prim’s root. Notice three things:

  1. Kruskal is global. It examines all graph edges by weight; fragments grow everywhere and merge.
  2. Prim is local. There is one tree and only outgoing edges matter. It follows Dijkstra’s pattern; a later figure compares their similarities and differences.
  3. Borůvka is naturally parallel. Each fragment chooses without consulting others. With nn vertices about log⁡2n\log_2 n phases suffice, because fragment count at least halves.

The figure graph is the points’ Gabriel graph (two points are connected if no other lies in the circle with their segment as diameter), plus some edges to nearby neighbors. This is deliberate: the Euclidean MST of planar points always lies inside the Gabriel graph, itself inside the Delaunay triangulation with O(n)\bigO(n) edges, so the complete graph’s (n2)\binom{n}{2} edges need not be examined. Thus the figure’s tree is the points’ Euclidean MST: extra edges would not change it.

The organizing question is why such different algorithms produce the same tree.

Why they work: cuts and cycles

A cut of GG is a vertex partition (S,V∖S)(S, V \setminus S) with S≠∅S \neq \emptyset and S≠VS \neq V. An edge crosses the cut if it has one endpoint on each side. Edge set AA respects the cut if no edge of AA crosses it. A light cut edge has minimum weight among crossing edges.

Proof

Let TT be an MST with A⊆TA \subseteq T. If e∈Te \in T there is nothing to prove, so suppose e∉Te \notin T. Adding ee to TT creates exactly one cycle CC, passing through ee. A cycle crosses a cut an even number of times (each departure must return), and ee already crosses it, so CC contains another crossing edge f≠ef \neq e. Since AA respects the cut, f∉Af \notin A. Let T′=(T∖{f})∪{e}T' = (T \setminus \{f\}) \cup \{e\}. Removing an edge from a cycle does not disconnect, and edge count remains n−1n - 1, so T′T' is a spanning tree. Its weight is

w(T′)=w(T)−w(f)+w(e)≤w(T),w(T') = w(T) - w(f) + w(e) \le w(T),

because ee is light and ff crosses the cut. Thus T′T' is also minimum and contains AA (since f∉Af \notin A) and ee.

∎

The next figure lets you test the property: draw a cut and verify the green edge always lies in the MST.

InteractiveThe cut property with the mouse
23.028.431.131.633.851.1
  • side SS
  • side V∖SV \setminus S
  • edge crossing the cut
  • lightest crossing edge
  • rest of minimum tree
The cut leaves 6 vertices on one side and 6 on the other. It is crossed by 6 edges (amber); the lightest, weight 23.0 (green), belongs to the minimum tree. Click another amber edge to see the cost of using it instead of the green one.
Draw the cut
What to show
Vertices on each side6 and 6
Crossing edges6
Lightest edge23.0
In the minimum tree?yes
Minimum tree284.4
Best tree with chosen edge and without lightest289.8 (+5.4)
Drag both line endpoints to draw a cut (or switch to ‘Vertices’ and mark points on each side). Amber edges cross it; the lightest, green, always lies in the MST (the rest gray). Click another amber edge and switch to ‘Exchange’: the figure shows the best tree avoiding green and using amber, which weighs more; restoring green closes a red cycle crossing the cut by another edge, and exchanging them is exactly the proof step. Find cuts with one crossing edge and cuts whose green edge is longest in the tree.

Two observations. The cut need not be “reasonable”: any partition works, however odd. A stronger version follows from the same proof with strict inequality: if the cut has a unique light edge ee, then ee belongs to every MST (otherwise exchange produces a strictly lighter tree, absurd). Figure weights are distinct, so green is always its cut’s unique light edge and belongs to the unique MST.

Proof

Suppose an MST TT contains ee. Removing ee splits TT into two components, defining a cut (S,V∖S)(S, V \setminus S) crossed by ee. Path C∖{e}C \setminus \{e\} joins ee‘s endpoints and thus crosses that cut via some edge f∈C∖{e}f \in C \setminus \{e\}. Then T′=(T∖{e})∪{f}T' = (T \setminus \{e\}) \cup \{f\} is a spanning tree with w(T′)=w(T)−w(e)+w(f)<w(T)w(T') = w(T) - w(e) + w(f) < w(T), contradicting minimality of TT.

∎

If ee is merely one of the heaviest cycle edges (ties), the same exchange gives w(T′)≤w(T)w(T') \le w(T): some MST excludes ee. In matroid language from the greedy lesson, graph cycles are graphic matroid circuits and minimal cuts (by inclusion, separating a connected component into exactly two) are cocircuits: the properties are dual.

The two properties ensure distinct weights give a unique MST. Its exchange proof is a good exercise at the end, and uniqueness permits unambiguous reasoning about all three algorithms.

The generic algorithm

The properties yield an algorithm maintaining set AA with invariant “AA lies in some MST”:

  1. Start with A=∅A = \emptyset, satisfying the invariant.
  2. While AA is not a tree, choose a cut respected by AA and add one of its light edges to AA. Such an edge is safe for AA.

The cut property preserves the invariant; when AA has n−1n - 1 edges it is a tree contained in an MST, hence minimum. What remains is which cut to choose, where the algorithms differ:

AlgorithmCut usedEdge added
Kruskalone fragment of AA versus the restlightest in the graph joining distinct fragments
Primtree V(T)V(T) versus the restlightest leaving the tree
Borůvkaeach fragment versus the rest, all at oncelightest leaving each fragment

In all three cases AA respects the cut because its edges lie within fragments.

Kruskal

The only hard question is whether each edge closes a cycle; union-find answers exactly that: vertices are connected iff they share a representative, and accepting an edge is a union.

Correctness. When Kruskal accepts e=(u,v)e = (u, v), let CC be the component of AA containing uu; cut (C,V∖C)(C, V \setminus C) is respected by AA and crossed by ee. Every edge lighter than ee was already examined and either accepted (thus inside a component) or discarded because endpoints were connected and remain so. No lighter edge crosses the cut: ee is light and safe. When Kruskal rejects ee, an accepted-edge path, all lighter, joins its endpoints; ee is heaviest in their cycle and the cycle property says it is unnecessary. Acceptance follows from the cut, rejection from the cycle.

Cost. Sorting costs O(mlog⁡m)=O(mlog⁡n)\bigO(m \log m) = \bigO(m \log n), because m≤n2m \le n^2 gives log⁡m≤2log⁡n\log m \le 2\log n. Traversal performs at most mm finds and n−1n - 1 unions, costing O(m α(m,n))\bigO(m\,\alpha(m, n)) (inverse Ackermann function). Sorting dominates. Bounded integer weights allow linear bucket sorting, making total cost O(m α)\bigO(m\,\alpha). If edges arrive sorted or only the lightest need examination, early stopping saves almost everything. A modern variant, Filter-Kruskal, partitions edges like quicksort and discards cycle-closing edges early, improving practice.

Kruskal is also the graphic matroid greedy algorithm: independent sets are forests and bases are spanning trees. With weights ww, the greedy lesson’s Rado–Edmonds theorem proves correctness another way without new work.

Prim

Correctness follows immediately from the cut property: at each step A=TA = T respects cut (V(T),V∖V(T))(V(T), V \setminus V(T)) because all its edges lie within V(T)V(T), and the added edge is light for that cut.

Cost depends on key storage. The important operation is decreasing the key of an already queued neighbor, requiring an indexed queue:

Key structureTotal costWhen useful
unsorted arrayO(n2)\bigO(n^2)dense graph (m≈n2m \approx n^2), also vectorizable
indexed binary heapO(mlog⁡n)\bigO(m \log n)sparse graph
dd-ary heap with d=max⁡(2,⌈m/n⌉)d = \max(2, \lceil m/n \rceil)O(mlog⁡2+m/nn)\bigO(m \log_{2 + m/n} n)almost always, simple
Fibonacci heapO(m+nlog⁡n)\bigO(m + n \log n)Prim’s best comparison-priority-queue bound

The array wins on dense graphs: with m=Θ(n2)m = \Theta(n^2) it costs O(m)\bigO(m), linear, with no structure overhead. Fibonacci heaps rarely pay off in practice due to constants but set Prim’s theoretical bound.

Prim and Dijkstra: one line apart

Prim resembles Dijkstra enough to confuse them. Both grow a tree by repeatedly extracting the smallest-key vertex. Only the key differs:

  • Prim: clave(v)=min⁡u∈Tw(u,v)\text{clave}(v) = \min_{u \in T} w(u, v), weight of one edge.
  • Dijkstra: clave(v)=min⁡u∈T(dist(u)+w(u,v))\text{clave}(v) = \min_{u \in T}\big(\text{dist}(u) + w(u, v)\big), length of a path from the root.
InteractivePrim and Dijkstra one line apart
23.438.225.437.1
  • Prim tree
  • best edge for each frontier vertex (with its key)
  • the one entering now
  • Dijkstra tree (final)
vertex 1 / 14
Start at the root. Each frontier vertex’s key is the weight of its edge to the tree.
Vertex key
14
Final tree weightPrim 308.0 · Dijkstra 365.2
Mean distance to rootPrim 102.2 · Dijkstra 58.3
Maximum distance to rootPrim 187.0 · Dijkstra 90.0
Edges differing between them6
The same loop and graph with two key rules. Numbers by frontier vertices are keys; the dashed orange edge is next. ‘Overlay’ draws the other rule's final tree as a faint thick line. Prim always wins in total tree weight, Dijkstra in root distance (mean and maximum). Click a vertex to change root and change graphs: on these geometric graphs the trees almost never match, because the shortest-path tree fans out from the root and the MST joins nearby neighbors.

Dijkstra’s tree minimizes each root distance; Prim’s minimizes total weight, and they need not coincide: an MST does not contain all-pairs shortest paths. The smallest example is a triangle with weights w(s,a)=1w(s, a) = 1, w(a,b)=1w(a, b) = 1 and w(s,b)=1.5w(s, b) = 1.5: its MST is {sa,ab}\{sa, ab\} of weight 22, but the shortest path from ss to bb is the direct edge of length 1.51.5, omitted by the MST.

Borůvka

Correctness. Each chosen edge is light for the cut “one fragment versus the rest”, respected by AA, so each is individually safe. But all are added simultaneously: the cut property guarantees one edge is safe, not that all together are. Distinct weights resolve this: each fragment’s choice is its cut’s unique light edge, hence belongs to every MST, namely the unique MST; all choices are a subset of that tree and cannot form cycles.

Phase count. In a connected graph each fragment has an outgoing edge, and every new fragment merges at least two old ones. Fragment count therefore at least halves each phase and ⌈log⁡2n⌉\lceil \log_2 n \rceil phases suffice. Each costs O(m)\bigO(m) (one edge pass finding each fragment’s minimum), totaling O(mlog⁡n)\bigO(m \log n). If the graph is contracted after each phase (fragments become vertices; loops and parallel edges are removed, retaining the lightest), planar-graph edge count remains proportional to vertices and costs sum geometrically: O(n)\bigO(n) total.

Parallelism. Each fragment chooses independently. On a GPU or distributed system this takes O(log⁡n)\bigO(\log n) rounds, each with work O(m)\bigO(m) and small depth. Borůvka therefore underpins parallel MST algorithms and the Karger–Klein–Tarjan implementation below.

Implementation from scratch

All three algorithms on the same graph and checks. First union-find and Kruskal; then Prim with an indexed queue (lesson 6’s compact version) and, for dense graphs, vectorized-array Prim; finally NumPy-vectorized Borůvka, using each edge’s rank for tie-breaking and merging fragments by pointer jumping (each fragment points to the opposite endpoint’s fragment, repeating destino[destino] until all point to a root).

[ ]Kruskal, Prim and Borůvka from scratch against SciPy and NetworkXBrowser
import time
import numpy as np
import networkx as nx
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import minimum_spanning_tree

INF = float("inf")

def grafo_aleatorio(n, m, seed):
    """Grafo conexo (un árbol aleatorio más aristas extra) con pesos distintos 1..m."""
    rng = np.random.default_rng(seed)
    perm = rng.permutation(n)
    pares = {tuple(sorted((int(perm[i]), int(perm[rng.integers(0, i)])))) for i in range(1, n)}
    while len(pares) < m:
        a, b = rng.integers(0, n, 2)
        if a != b:
            pares.add((int(min(a, b)), int(max(a, b))))
    pares = sorted(pares)
    u = np.array([p[0] for p in pares]); v = np.array([p[1] for p in pares])
    w = rng.permutation(len(pares)).astype(float) + 1.0
    return u, v, w

class DSU:
    """Union-find con unión por tamaño y reducción de caminos a la mitad."""
    def __init__(self, n):
        self.p = list(range(n)); self.t = [1] * n
    def buscar(self, x):
        p = self.p
        while p[x] != x:
            p[x] = p[p[x]]; x = p[x]
        return x
    def unir(self, a, b):
        a, b = self.buscar(a), self.buscar(b)
        if a == b:
            return False
        if self.t[a] < self.t[b]:
            a, b = b, a
        self.p[b] = a; self.t[a] += self.t[b]
        return True

def kruskal(n, u, v, w):
    dsu, arbol = DSU(n), []
    for e in np.argsort(w, kind="stable"):          # el coste lo domina esta ordenación
        if dsu.unir(u[e], v[e]):
            arbol.append(int(e))
            if len(arbol) == n - 1:                 # parada temprana: ya hay árbol
                break
    return sorted(arbol)

class ColaIndexada:
    """Montículo binario de mínimos sobre los elementos 0..n-1 con baja-clave (la de la lección 6, compacta)."""
    def __init__(self, n):
        self.clave = [INF] * n; self.pos = [-1] * n; self.h = []
    def _sube(self, i):
        h, pos, clave = self.h, self.pos, self.clave
        while i > 0:
            p = (i - 1) // 2
            if clave[h[p]] <= clave[h[i]]:
                break
            h[p], h[i] = h[i], h[p]; pos[h[p]], pos[h[i]] = p, i; i = p
    def _baja(self, i):
        h, pos, clave = self.h, self.pos, self.clave
        n = len(h)
        while True:
            m = i
            for c in (2 * i + 1, 2 * i + 2):
                if c < n and clave[h[c]] < clave[h[m]]:
                    m = c
            if m == i:
                return
            h[m], h[i] = h[i], h[m]; pos[h[m]], pos[h[i]] = m, i; i = m
    def bajar(self, x, k):
        """Inserta x con clave k, o le baja la clave si ya estaba."""
        self.clave[x] = k
        if self.pos[x] < 0:
            self.h.append(x); self.pos[x] = len(self.h) - 1
        self._sube(self.pos[x])
    def extraer(self):
        h, pos = self.h, self.pos
        x = h[0]; ultimo = h.pop(); pos[x] = -2
        if h:
            h[0] = ultimo; pos[ultimo] = 0; self._baja(0)
        return x

def lista_adyacencia(n, u, v, w):
    adj = [[] for _ in range(n)]
    for e in range(len(u)):
        adj[u[e]].append((int(v[e]), float(w[e]), e)); adj[v[e]].append((int(u[e]), float(w[e]), e))
    return adj

def prim(n, adj, raiz=0):
    cola, via, arbol = ColaIndexada(n), [-1] * n, []
    cola.bajar(raiz, 0.0)
    while cola.h:
        x = cola.extraer()
        if via[x] >= 0:
            arbol.append(via[x])
        for y, peso, e in adj[x]:
            if cola.pos[y] != -2 and peso < cola.clave[y]:   # la clave es el peso de la arista, NO una distancia
                via[y] = e
                cola.bajar(y, peso)
    return sorted(arbol)

def prim_denso(W):
    """Prim con array en O(n^2) sobre la matriz de pesos (inf = sin arista), vectorizado con NumPy."""
    n = len(W)
    dentro = np.zeros(n, bool); clave = np.full(n, INF); padre = np.full(n, -1)
    clave[0] = 0.0
    for _ in range(n):
        x = int(np.argmin(np.where(dentro, INF, clave)))
        dentro[x] = True
        mejor = (W[x] < clave) & ~dentro
        clave[mejor] = W[x][mejor]; padre[mejor] = x
    return padre, clave

def boruvka(n, u, v, w):
    """Borůvka vectorizado. Ordenando antes las aristas, el índice es un desempate total."""
    orden = np.argsort(w, kind="stable"); u, v = u[orden], v[orden]
    m = len(u); comp = np.arange(n); arbol = np.zeros(m, bool); fases = 0
    ids_v = np.arange(n)
    while True:
        cu, cv = comp[u], comp[v]
        fuera = np.nonzero(cu != cv)[0]
        if len(fuera) == 0:
            break
        fases += 1
        mejor = np.full(n, m)                                  # arista saliente más ligera de cada componente
        np.minimum.at(mejor, cu[fuera], fuera); np.minimum.at(mejor, cv[fuera], fuera)
        c = np.nonzero(mejor < m)[0]
        arbol[mejor[c]] = True
        e = mejor[c]
        destino = ids_v.copy()                                 # cada componente apunta a la del otro extremo
        destino[c] = np.where(cu[e] == c, cv[e], cu[e])
        mutuo = (destino[destino] == ids_v) & (ids_v < destino)  # parejas que eligieron la misma arista
        destino[mutuo] = ids_v[mutuo]                          # la menor de cada pareja será la raíz
        while True:                                            # salto de punteros: todo apunta a una raíz
            nuevo = destino[destino]
            if np.array_equal(nuevo, destino):
                break
            destino = nuevo
        comp = destino[comp]
    return sorted(int(x) for x in orden[arbol]), fases

# ---------- verificación contra SciPy y NetworkX en grafos aleatorios ----------
for n, m, semilla in [(60, 150, 0), (200, 900, 1), (500, 2500, 2)]:
    u, v, w = grafo_aleatorio(n, m, semilla)
    ref = minimum_spanning_tree(coo_matrix((w, (u, v)), shape=(n, n)).tocsr())
    peso_ref = ref.sum()
    G = nx.Graph(); G.add_weighted_edges_from(zip(u.tolist(), v.tolist(), w.tolist()))
    peso_nx = sum(d["weight"] for *_, d in nx.minimum_spanning_edges(G, algorithm="kruskal"))
    ka = kruskal(n, u, v, w)
    pr = prim(n, lista_adyacencia(n, u, v, w))
    bo, fases = boruvka(n, u, v, w)
    print(f"n={n:4d} m={m:5d}  pesos: scipy {peso_ref:.0f} networkx {peso_nx:.0f} | "
          f"Kruskal {w[ka].sum():.0f} Prim {w[pr].sum():.0f} Borůvka {w[bo].sum():.0f}  "
          f"mismas aristas: {ka == pr == bo}  fases de Borůvka: {fases} (cota {int(np.ceil(np.log2(n)))})")

# ---------- coste: grafo disperso y grafo denso ----------
def reloj(f, *a):
    t = time.perf_counter(); r = f(*a); return r, 1000 * (time.perf_counter() - t)

n, m = 2000, 10000
u, v, w = grafo_aleatorio(n, m, 7); adj = lista_adyacencia(n, u, v, w)
_, t1 = reloj(kruskal, n, u, v, w); _, t2 = reloj(prim, n, adj); _, t3 = reloj(boruvka, n, u, v, w)
print(f"\ndisperso n={n}, m={m}:   Kruskal {t1:6.1f} ms   Prim con montículo {t2:6.1f} ms   Borůvka {t3:6.1f} ms")

n = 400
rng = np.random.default_rng(3)
P = rng.random((n, 2)); D = np.hypot(*(P[:, None] - P[None]).transpose(2, 0, 1)); np.fill_diagonal(D, INF)
iu, ju = np.triu_indices(n, 1)
(padre, clave), t4 = reloj(prim_denso, D)
ka, t5 = reloj(kruskal, n, iu, ju, D[iu, ju])
bo, t6 = reloj(lambda: boruvka(n, iu, ju, D[iu, ju]))
print(f"denso n={n}, m={len(iu)}: Kruskal {t5:6.1f} ms   Prim con array {t4:6.1f} ms   Borůvka {t6:6.1f} ms   "
      f"(mismo peso: {abs(clave.sum() - D[iu, ju][ka].sum()) < 1e-9 and abs(clave.sum() - D[iu, ju][bo[0]].sum()) < 1e-9})")

# ---------- empates: Borůvka sin desempate crea ciclos ----------
rng = np.random.default_rng(0)
def fase_ingenua(n):
    """Grafo completo con todas las aristas de peso 1: cada vértice elige una arista incidente al azar."""
    elegidas = {tuple(sorted((x, int(rng.choice([y for y in range(n) if y != x]))))) for x in range(n)}
    dsu = DSU(n)
    return any(not dsu.unir(a, b) for a, b in elegidas)
for n in (3, 4, 6):
    ciclos = sum(fase_ingenua(n) for _ in range(2000))
    print(f"K{n} con pesos iguales y desempate al azar: {100 * ciclos / 2000:.0f} % de las fases elige un ciclo")

The first three output lines verify that Kruskal, Prim and Borůvka return the same edges (distinct weights give a unique tree) and match SciPy and NetworkX weights. Borůvka takes 3 or 4 phases on graphs up to 500 vertices, well below the ⌈log⁡2n⌉\lceil \log_2 n \rceil bound of 6–9: fragments typically shrink much faster than halving. Do not infer absolute timing winners from one interpreted run: visible work is sorting and finding for Kruskal, heap key movement for Prim, mm-length array operations for Borůvka, and O(n2)\bigO(n^2) for array Prim on dense graphs without any structure. The last three lines illustrate ties: with random tie-breaking, an equal-weight triangle chooses a cycle 25% of the time (two of 23=82^3 = 8 choices are cyclic), and the proportion grows with complete-graph size.

Can it be linear?

Reading mm edges already costs Ω(m)\Omega(m), so linear is optimal; the problem’s history approaches that floor:

AlgorithmYearTime
Borůvka1926O(mlog⁡n)\bigO(m \log n)
Kruskal, Prim with binary heap1956 and 1957O(mlog⁡n)\bigO(m \log n)
Prim with Fibonacci heaps (Fredman and Tarjan)1987O(m+nlog⁡n)\bigO(m + n \log n)
Fredman and Tarjan with bounded growth1987O(m β(m,n))\bigO(m\,\beta(m, n)), with β\beta nearly constant
Karger, Klein and Tarjan1995O(m)\bigO(m) expected, randomized
Chazelle2000O(m α(m,n))\bigO(m\,\alpha(m, n)), deterministic
Pettie and Ramachandran2002deterministic optimum, exact complexity unknown

Whether a deterministic linear algorithm exists remains open; Karger, Klein and Tarjan (KKT) reach the floor with randomness. They use this lesson’s properties and two ideas: sample edges to get a filtering forest, then discard edges that forest proves cannot be in the tree.

Heavy and light edges

Throughout this section weights are distinct (or ties use a total order, as in Borůvka), so the MST is unique. Let FF be a forest of GG (e.g. a subgraph’s minimum forest). For edge e=(u,v)e = (u, v), if uu and vv lie in different trees of FF, call ee FF-light; otherwise it is FF-light if w(e)w(e) is less than the largest weight on their path in FF (or if e∈Fe \in F), and FF-heavy otherwise.

Proof

The path of FF between ee‘s endpoints together with ee forms a cycle in which ee is strictly heaviest. By the cycle property it is in no MST.

∎

Filtering with FF can make the problem much smaller. How much? Randomness answers.

Proof

Traverse edges of GG from lightest to heaviest, flipping a coin per edge (heads with probability pp means “in HH”), maintaining forest FiF_i built by Kruskal from HH edges seen so far. For an edge ee, forest FF restricted to edges lighter than ee is exactly that partial forest, and ee is FF-light iff its endpoints are not connected by FF edges lighter than ee (otherwise the unique path has all edges lighter than ee and ee is heavy; otherwise they are disconnected or the path uses a heavier edge and ee is light). In other words ee is FF-light iff it joins two components of partial forest FiF_i.

Each examined light edge’s coin independently lands heads with probability pp, and then the edge enters FF and component count falls by one. This happens at most n−1n - 1 times. The number of light edges is therefore at most the number of tosses until n−1n - 1 heads, a negative binomial with expectation (n−1)/p(n-1)/p.

∎

With p=1/2p = 1/2 and nn vertices, at most 2n2n light edges remain in expectation regardless of how many GG had. This is the algorithm’s core idea.

The algorithm

Correctness follows: CC edges are safe (Borůvka); deleted edges are heavy relative to a forest and absent from the MST (heavy-edge theorem); and the tree of G′G' lies inside G′′G'', containing FF.

Expected time. Let nn and mm be input sizes. Steps 1 and 3 cost O(n+m)\bigO(n + m). Subproblem HH has n/4n/4 vertices and expected m/2m/2 edges. Subproblem G′′G'' has n/4n/4 vertices and, by the sampling lemma with p=1/2p = 1/2, at most (n/4)/(1/2)=n/2(n/4)/(1/2) = n/2 expected edges. Thus

T(n,m)≤T ⁣(n4,m2)+T ⁣(n4,n2)+c (n+m).T(n, m) \le T\!\left(\tfrac{n}{4}, \tfrac{m}{2}\right) + T\!\left(\tfrac{n}{4}, \tfrac{n}{2}\right) + c\,(n + m).

Induction verifies T(n,m)≤4c n+2c mT(n, m) \le 4c\,n + 2c\,m: substituting, the two subproblems contribute (cn+cm)+(cn+cn)\big(cn + cm\big) + \big(cn + cn\big) and local work cn+cmcn + cm, summing to 4cn+2cm4cn + 2cm. That is, expected O(n+m)\bigO(n + m) time. Worst-case cost is no worse than O(min⁡{n2,mlog⁡n})\bigO(\min\{n^2, m \log n\}), Borůvka’s.

[ ]Measuring the Karger–Klein–Tarjan sampling lemmaBrowser
import numpy as np

class DSU2:
    def __init__(self, n):
        self.p = list(range(n))
    def buscar(self, x):
        while self.p[x] != x:
            self.p[x] = self.p[self.p[x]]; x = self.p[x]
        return x
    def unir(self, a, b):
        a, b = self.buscar(a), self.buscar(b)
        if a != b:
            self.p[a] = b
        return a != b

def grafo_ordenado(n, m, seed):
    """Aristas ordenadas por peso creciente (la posición es el peso: todos distintos)."""
    rng = np.random.default_rng(seed)
    perm = rng.permutation(n)
    pares = {tuple(sorted((int(perm[i]), int(perm[rng.integers(0, i)])))) for i in range(1, n)}
    while len(pares) < m:
        a, b = rng.integers(0, n, 2)
        if a != b:
            pares.add((int(min(a, b)), int(max(a, b))))
    pares = sorted(pares)
    return [pares[i] for i in np.argsort(rng.permutation(len(pares)))]

def ligeras_por_conteo(n, aristas, p, rng):
    """Una pasada de Kruskal con una moneda por arista: cuenta las F-ligeras de la F obtenida con las muestreadas."""
    dsu, ligeras, F = DSU2(n), [], []
    for i, (a, b) in enumerate(aristas):
        if dsu.buscar(a) != dsu.buscar(b):       # une dos componentes de las muestreadas más ligeras: F-ligera
            ligeras.append(i)
            if rng.random() < p:                 # y entonces, con probabilidad p, entra en la muestra (y en F)
                dsu.unir(a, b); F.append(i)
    return ligeras, F

def ligeras_por_definicion(n, aristas, F):
    """Definición: e es F-ligera si sus extremos están en árboles distintos de F o pesa menos que el máximo del camino en F."""
    adj = {x: [] for x in range(n)}
    for i in F:
        a, b = aristas[i]; adj[a].append((b, i)); adj[b].append((a, i))
    def max_camino(a, b):
        pila, visto = [(a, -1)], {a}
        while pila:
            x, mx = pila.pop()
            if x == b:
                return mx
            for y, i in adj[x]:
                if y not in visto:
                    visto.add(y); pila.append((y, max(mx, i)))
        return None                              # no conectados en F
    return [i for i, (a, b) in enumerate(aristas) if (mx := max_camino(a, b)) is None or i <= mx]

# 1) el recuento de una pasada coincide con la definición, y el árbol mínimo cabe en las ligeras
rng = np.random.default_rng(1)
n, m = 40, 200
aristas = grafo_ordenado(n, m, 5)
ligeras, F = ligeras_por_conteo(n, aristas, 0.5, rng)
print("coinciden con la definición (camino máximo en F):", ligeras == ligeras_por_definicion(n, aristas, F))
dsu, arbol = DSU2(n), set()
for i, (a, b) in enumerate(aristas):
    if dsu.unir(a, b):
        arbol.add(i)
print(f"el árbol mínimo ({len(arbol)} aristas) está dentro de las ligeras ({len(ligeras)} de {m}): {arbol <= set(ligeras)}")

# 2) lema de muestreo: E[aristas ligeras] <= (n-1)/p
n, m, intentos = 200, 2000, 60
aristas = grafo_ordenado(n, m, 11)
print()
for p in (0.5, 0.25, 0.1):
    cuentas = [len(ligeras_por_conteo(n, aristas, p, rng)[0]) for _ in range(intentos)]
    ee = np.std(cuentas) / np.sqrt(intentos)
    print(f"p = {p:4}: media {np.mean(cuentas):6.1f} ± {ee:4.1f}   cota (n-1)/p = {(n - 1) / p:6.1f}   "
          f"máximo observado {max(cuentas)}   (m = {m})")

The first check validates the proof: one-pass counting (the lemma’s technique) returns exactly edges that definition calls FF-light, and the MST lies inside them, as it must. The second measures the lemma: with p=1/2p = 1/2 and p=1/4p = 1/4 the observed mean matches bound (n−1)/p(n-1)/p within sampling error (nearly equality while enough edges remain), and of 20002000 graph edges roughly 400400 and 800800 survive. With p=0.1p = 0.1 the bound becomes unattainable because the graph runs out of edges to examine.

Variants: what the MST does and does not see

Weight transformations

Kruskal only compares weights: the tree depends solely on edge order. Thus any strictly increasing weight transformation preserves the MST, while order-changing transformations can change it.

TransformationPreserves MST?Reason
w+cw + c (add a constant)yesevery tree has n−1n - 1 edges, so all gain (n−1)c(n-1)c
w2w^2, with w≥0w \ge 0yesx↦x2x \mapsto x^2 is strictly increasing in [0,∞)[0, \infty)
w2w^2 with weights of both signsno−5-5 and 33 become 2525 and 99: order reverses
log⁡w\log w, with w>0w > 0yesincreasing. Also ∑log⁡w=log⁡∏w\sum \log w = \log \prod w: minimizes the weight product
−w-wnogives the maximum spanning tree

Adding a constant preserves the MST but not shortest paths, which change because paths with more edges are penalized more: another difference from Dijkstra. A maximum spanning tree (e.g. Chow–Liu) uses the same algorithm with negated weights. The maximum-reliability tree maximizing the product of link-working probabilities pep_e is the MST with weights −log⁡pe-\log p_e, combining the last two rows.

The bottleneck

The bottleneck weight of tree TT is b(T)=max⁡e∈Tw(e)b(T) = \max_{e \in T} w(e). A minimum bottleneck spanning tree (MBST) minimizes bb. This is a different objective, but the MST satisfies it.

Proof

Let ee be TT‘s heaviest edge, with w(e)=b(T)w(e) = b(T), and suppose T′T' exists with b(T′)<w(e)b(T') < w(e). Removing ee from TT gives cut (S,V∖S)(S, V \setminus S); as a spanning tree, T′T' must have a crossing edge ff, and w(f)≤b(T′)<w(e)w(f) \le b(T') < w(e). But then T∖{e}∪{f}T \setminus \{e\} \cup \{f\} is a lighter spanning tree than TT, absurd.

∎

The converse is false. In a square with weights w(ab)=1w(ab) = 1, w(bc)=4w(bc) = 4, w(cd)=2w(cd) = 2, w(da)=4w(da) = 4, tree {ab,cd,bc}\{ab, cd, bc\} weighs 7 with bottleneck 4, and {ab,bc,da}\{ab, bc, da\} weighs 9 with bottleneck 4: both minimize bottleneck and only one is minimum weight. The coding exercise implements this and checks Kruskal also solves bottleneck.

A finer version useful for clustering: between any two vertices, the MST path is a minimax path.

Proof

Let ee be PP‘s heaviest edge and suppose a path QQ from uu to vv has all edges lighter than w(e)w(e). Removing ee from TT puts vertices uu and vv on opposite sides of the cut (their path in TT used ee). QQ joins uu to vv and crosses the cut via edge ff with w(f)<w(e)w(f) < w(e), making T∖{e}∪{f}T \setminus \{e\} \cup \{f\} a lighter tree. Contradiction.

∎

Ties

Repeated weights make the MST nonunique (the count uses the matrix-tree theorem, topic of m25), but all MSTs have the same multiset of weights. For each threshold hh, the count of edges of weight ≤h\le h in any MST is n−c(h)n - c(h), where c(h)c(h) is the component count of subgraph G≤hG_{\le h} of edges with weight ≤h\le h. By the preceding theorem, vertices connected in G≤hG_{\le h} have a minimax path in TT using only edges of weight ≤h\le h, so edges of TT with weight ≤h\le h form a spanning forest of G≤hG_{\le h} with n−c(h)n - c(h) edges. Subtract consecutive thresholds to fix the count of each exact weight. The tree’s weight profile is a graph property, not an algorithm property; clustering will use it.

Applications

Single linkage and dendrograms

Single-linkage hierarchical clustering defines distance between groups as the minimum distance between one point from each, merging the closest groups each step. Each merge is a Kruskal edge on the complete distance graph, so the merge sequence is Kruskal’s execution and heights are MST weights in increasing order. Cutting the dendrogram at hh means stopping Kruskal at edges heavier than hh: clusters are components of tree edges weighted ≤h\le h.

InteractiveFrom MST to dendrogram
0102030h = 20.6height
  • cluster (color) below the cut
  • cut tree edge
  • threshold hh
With h = 20.6, 3 clusters remain: 12 + 11 + 11. 2 tree edges are cut.
Data
20.6
Clusters3
Sizes12 + 11 + 11
Cut edges2
Largest gap between merges20.9 (at 3 clusters)
The first panel shows planar points with their Euclidean MST (Prim on the complete graph). The second is the single-linkage dendrogram: each horizontal merge is a tree edge at its height. Move threshold hh using the slider or by dragging on the dendrogram: tree edges longer than hh are cut (dashed red), and remaining colored components are clusters; the orange dendrogram line leaves exactly those clusters below. ‘Best cut’ finds the biggest jump between consecutive merges. With ‘Two moons’ single linkage follows elongated shapes a center method would not separate; with ‘Bridge between groups’ observe chaining: a row of points joins two groups whose centers are 60 apart with merges of just 6 to 13 units, the dendrogram has no clear jump and the two-cluster cut falls on the tree's longest edge, often isolating one point or splitting the chain instead of separating groups.
Proof

If connected in the tree forest, they are connected by a chain of ≤h\le h jumps. Conversely, a chain of ≤h\le h jumps from uu to vv is an GG path of maximum weight ≤h\le h. By the minimax-path theorem, the MST path between uu and vv has maximum weight at most ≤h\le h and lies in the forest.

∎

Merge distances also define an ultrametric (the height where two points merge, i.e. maximum weight of their minimax path satisfies d(u,w)≤max⁡{d(u,v),d(v,w)}d(u, w) \le \max\{d(u, v), d(v, w)\}, since concatenating two minimax paths gives a path from uu to ww).

A related problem is maximum-spacing clustering: group points into kk clusters maximizing minimum distance between points in different clusters (spacing). Cut the MST’s k−1k - 1 heaviest edges. To prove this, let d∗d^* be the lightest cut-edge weight: the resulting kk clusters have spacing exactly d∗d^*. The cut edge of weight d∗d^* joins different clusters, and any pair pp, qq in different clusters has distance ≥d∗\ge d^*: their tree path crosses a cut edge of weight ≥d∗\ge d^* and by the minimax theorem direct edge pqpq weighs at least the path maximum. All retained edges weigh ≤d∗\le d^*. If another grouping into kk clusters differs, one of our clusters contains points pp and qq in different clusters of the other. Their tree path from pp to qq lies within our cluster, all edges weigh ≤d∗\le d^*, and some edge joins different clusters of the other grouping. Its spacing is at most d∗d^*.

Ties among the heaviest edges introduce a detail: there may be no threshold hh producing exactly kk clusters. You will see this in an exercise.

Chaining is a real single-linkage weakness: a row of points can join two dense groups, and one outlier reduces spacing. Variants exist: HDBSCAN computes the same tree on a locally density-adjusted distance and cuts using stability rather than a threshold.

The Chow–Liu tree

Given dd discrete random variables with joint distribution pp, seek the best approximation qTq_T with tree structure TT (each variable depends on at most one other). With pp‘s marginals and conditionals as parameters,

KL⁡(p ∥ qT)=−∑(i,j)∈TI(Xi;Xj)+∑iH⁡(Xi)−H⁡(X),\KL(p \,\|\, q_T) = -\sum_{(i,j) \in T} I(X_i; X_j) + \sum_i \Ent(X_i) - \Ent(X),

and the last two terms do not depend on TT. Minimizing divergence maximizes the sum of mutual information over tree edges: a maximum spanning tree of the complete graph with weight I(Xi;Xj)I(X_i; X_j), computed by reversed-order Kruskal in O(d2log⁡d)\bigO(d^2 \log d). With data use empirical mutual information. This is the Chow–Liu tree, covered in m14.

Metric traveling salesperson approximation

Metric traveling salesperson visits nn points with triangle-inequality distances and returns to the source by the shortest tour. It is NP-hard, but the MST gives a nearly free 22-approximation.

Proof

Removing an edge from an optimal Hamiltonian circuit leaves a path that is a spanning tree, so w(T)≤OPTw(T) \le \text{OPT}. Doubling edges of TT gives a connected multigraph of even degrees, admitting an Eulerian circuit of length 2 w(T)2\,w(T). Traverse it skipping already visited vertices: shortcuts replace subwalks and, by triangle inequality, do not lengthen them, leaving a Hamiltonian circuit (preorder of TT) of length ≤2 w(T)≤2 OPT\le 2\,w(T) \le 2\,\text{OPT}.

∎

Christofides’ algorithm (1976) replaces doubling with a minimum-weight perfect matching among odd-degree vertices, achieving factor 3/23/2; see the approximation lesson.

First compare single linkage with libraries against what we proved.

[ ]Single linkage: cut MST versus SciPyBrowser
import numpy as np
import networkx as nx
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import linkage, fcluster, cophenet

rng = np.random.default_rng(4)
X = np.vstack([rng.normal(c, 0.35, size=(20, 2)) for c in ([0, 0], [3, 0.5], [1.2, 3.2])])
n = len(X)
D0 = squareform(pdist(X))
D = D0 + np.diag(np.full(n, np.inf))                 # diagonal infinita: sin lazos (misma convención que la celda de Prim)
Z = linkage(X, method="single")

# árbol mínimo euclídeo con el Prim denso de la celda anterior
padre, clave = prim_denso(D)
aristas = sorted((float(clave[v]), int(padre[v]), v) for v in range(1, n))     # (peso, u, v) del árbol mínimo
print("alturas de fusión de linkage('single') = pesos del árbol mínimo ordenados:", np.allclose([a[0] for a in aristas], Z[:, 2]))

def etiquetas_cortando(aristas, k):
    """k clusters: se borran las k-1 aristas más pesadas del árbol y se etiquetan las componentes."""
    conservadas = aristas[: len(aristas) - (k - 1)]
    G = nx.Graph(); G.add_nodes_from(range(n)); G.add_edges_from((u, v) for _, u, v in conservadas)
    lab = np.zeros(n, int)
    for c, comp in enumerate(nx.connected_components(G)):
        lab[list(comp)] = c
    return lab

def misma_particion(a, b):
    return len({(x, y) for x, y in zip(a, b)}) == len(set(a)) == len(set(b))

for k in (2, 3, 5, 8):
    print(f"k = {k}: cortar el árbol = fcluster(maxclust)? {misma_particion(etiquetas_cortando(aristas, k), fcluster(Z, k, 'maxclust'))}")

# distancia cofenética (altura a la que se unen dos puntos) = camino minimax en el grafo completo
coph = squareform(cophenet(Z))
M = D0.copy()
for k in range(n):                                    # Floyd-Warshall con (min, max) en lugar de (min, +)
    M = np.minimum(M, np.maximum(M[:, k:k + 1], M[k:k + 1, :]))
print("cofenética = camino de cuello de botella del grafo completo:", np.allclose(coph, M))

# ultramétrica: d(u,w) <= max(d(u,v), d(v,w)) para todas las ternas
viola = sum(coph[i, j] > max(coph[i, k], coph[k, j]) + 1e-12 for i in range(0, n, 6) for j in range(0, n, 6) for k in range(0, n, 6))
print("ternas que violan la desigualdad ultramétrica:", viola)

The cell reuses prim_denso from above and checks the three claims: linkage heights are MST weights, cutting its k−1k - 1 heaviest edges gives the same partition as fcluster(..., 'maxclust'), and cophenetic distance is the bottleneck path (computed here with Floyd–Warshall over (min⁡,max⁡)(\min, \max) product rather than (min⁡,+)(\min, +), the shortest-path scheme), satisfying the ultrametric inequality.

Next compare the traveling salesperson approximation against the exact subset-DP optimum on 8-point instances.

[ ]Metric traveling salesperson: MST tour versus exact optimumBrowser
import numpy as np
from itertools import combinations

def mst_prim(D):
    n = len(D)
    dentro = np.zeros(n, bool); clave = np.full(n, np.inf); padre = np.full(n, -1); clave[0] = 0
    for _ in range(n):
        x = int(np.argmin(np.where(dentro, np.inf, clave))); dentro[x] = True
        mejor = (D[x] < clave) & ~dentro
        clave[mejor] = D[x][mejor]; padre[mejor] = x
    return [(int(padre[v]), v) for v in range(1, n)], clave.sum()

def recorrido_doble_arbol(D):
    """2-aproximación: recorrido en preorden del árbol mínimo (equivale a un circuito euleriano con atajos)."""
    aristas, peso_arbol = mst_prim(D)
    hijos = {x: [] for x in range(len(D))}
    for p, v in aristas:
        hijos[p].append(v)
    orden, pila = [], [0]
    while pila:
        x = pila.pop(); orden.append(x); pila.extend(reversed(hijos[x]))
    longitud = sum(D[orden[i], orden[(i + 1) % len(D)]] for i in range(len(D)))
    return longitud, peso_arbol

def optimo_held_karp(D):
    """Longitud del mejor circuito por programación dinámica sobre subconjuntos: O(2^n n^2)."""
    n = len(D)
    f = {(1 << j, j): D[0, j] for j in range(1, n)}
    for tam in range(2, n):
        for sub in combinations(range(1, n), tam):
            S = sum(1 << j for j in sub)
            for j in sub:
                f[(S, j)] = min(f[(S ^ (1 << j), i)] + D[i, j] for i in sub if i != j)
    todos = (1 << n) - 2
    return min(f[(todos, j)] + D[j, 0] for j in range(1, n))

rng = np.random.default_rng(2)
razones, sobre_arbol = [], []
for _ in range(25):
    P = rng.random((8, 2))
    D = np.hypot(*(P[:, None] - P[None]).transpose(2, 0, 1))
    tour, arbol = recorrido_doble_arbol(D)
    opt = optimo_held_karp(D)
    assert arbol <= opt + 1e-12 and opt <= tour + 1e-12 and tour <= 2 * arbol + 1e-12
    razones.append(tour / opt); sobre_arbol.append(opt / arbol)
print("25 instancias de 8 puntos: árbol <= óptimo <= recorrido <= 2 * árbol, siempre")
print(f"recorrido / óptimo: media {np.mean(razones):.3f}, peor {max(razones):.3f}   (garantía: 2)")
print(f"óptimo / árbol: media {np.mean(sobre_arbol):.3f}, máximo {max(sobre_arbol):.3f}")

The proof’s inequalities hold on all 25 instances (checked by assertion), and the factor-2 guarantee is pessimistic: tours average 13 %13\,\% longer than optimum, with sample worst case 32 %32\,\%. The optimum is between 11 and almost 1.751.75 times tree weight, making the MST a useful branch-and-bound lower bound.

With libraries

SciPy and NetworkX provide MSTs. Their conventions matter because of three traps.

FunctionWhat it doesCaution
scipy.sparse.csgraph.minimum_spanning_tree(G)Kruskal in C on sparse or dense matrixzero weights mean no edge; silently returns a forest for disconnected graphs
networkx.minimum_spanning_tree(G, algorithm=...)"kruskal" (default), "prim" or "boruvka"pure Python; forest on disconnected graphs; maximum_spanning_tree exists
scipy.cluster.hierarchy.linkage(X, "single")single linkage in O(n2)\bigO(n^2)MST-based algorithm; heights are its weights
scipy.spatial.DelaunayEuclidean MST candidate edges in O(nlog⁡n)\bigO(n \log n)obtain the tree by running Kruskal only on these edges
[ ]SciPy and NetworkX: zero weights and disconnected graphsBrowser
import numpy as np
import networkx as nx
from scipy.sparse import csr_matrix, coo_matrix
from scipy.sparse.csgraph import minimum_spanning_tree, connected_components

# triángulo 0-1 (peso 0), 1-2 (peso 2), 0-2 (peso 5): el árbol mínimo es {01, 12}, de peso 2
fila, col, peso = [0, 1, 0], [1, 2, 2], [0.0, 2.0, 5.0]
A = coo_matrix((peso, (fila, col)), shape=(3, 3)).tocsr()
print("aristas almacenadas en la matriz dispersa:", A.nnz)           # el cero explícito sí se almacena
T = minimum_spanning_tree(A)
print("scipy: aristas del árbol devueltas:", T.nnz, "(el árbol debería tener 2); peso:", T.sum())
print("networkx:", sorted(nx.minimum_spanning_tree(nx.Graph([(0, 1, {"weight": 0.0}), (1, 2, {"weight": 2.0}), (0, 2, {"weight": 5.0})])).edges))

# remedio: sumar una constante a todos los pesos NO cambia el árbol mínimo (todo árbol tiene n-1 aristas)
A2 = A.copy(); A2.data = A2.data + 1.0
T2 = minimum_spanning_tree(A2)
print("con pesos + 1: aristas", T2.nnz, " peso real:", T2.sum() - T2.nnz)

# grafo no conexo: scipy y networkx devuelven un bosque, sin avisar
B = csr_matrix(([1.0, 2.0], ([0, 2], [1, 3])), shape=(4, 4))
ncomp, _ = connected_components(B, directed=False)
print("componentes:", ncomp, "-> aristas del bosque:", minimum_spanning_tree(B).nnz, "(n - componentes =", 4 - ncomp, ")")

# los tres algoritmos de networkx coinciden con nuestra versión (grafo y funciones de la primera celda)
u, v, w = grafo_aleatorio(300, 1500, 21)
G = nx.Graph(); G.add_weighted_edges_from(zip(u.tolist(), v.tolist(), w.tolist()))
pesos = {alg: sum(d["weight"] for *_, d in nx.minimum_spanning_edges(G, algorithm=alg)) for alg in ("kruskal", "prim", "boruvka")}
print("pesos de networkx por algoritmo:", pesos, "  el nuestro:", w[kruskal(300, u, v, w)].sum())

The first line confirms the surprising trap: the sparse matrix does store zero, but SciPy returns a tree missing an edge and a seemingly correct weight (2.0) by chance. Our proof gives the solution: adding a positive constant leaves the MST unchanged, and subtracting it n−1n - 1 times recovers actual weight. After adding one, the two expected edges and true weight 2.0 appear. All three NetworkX algorithms match ours, as expected.

Common mistakes

Exercises

NumericMST weight for a 6-vertex graph
The graph has vertices A, B, C, D, E, F and weighted edges: AC = 1, BD = 2, EF = 3, CE = 4, AE = 5, DF = 6, AB = 7, CD = 8, BC = 9. What is its MST weight?
NumericBorůvka phases
For the previous graph (AC = 1, BD = 2, EF = 3, CE = 4, AE = 5, DF = 6, AB = 7, CD = 8, BC = 9), how many phases does Borůvka need to reach one fragment?
NumericSampling lemma bound
In a Karger–Klein–Tarjan call the input graph has 4000 vertices. After two Borůvka phases at most n′n' vertices remain, and each edge is sampled with probability 1/21/2. What is the bound n′/pn'/p on the expected number of F-light edges passed to the final recursive call?
NumericThe shortest-path tree is not the MST
A triangle with vertices ss, aa, bb has weights w(s,a)=1w(s, a) = 1, w(a,b)=1w(a, b) = 1 and w(s,b)=1.5w(s, b) = 1.5. What is the weight of the shortest-path tree from ss (built by Dijkstra)?
NumericCluster counts impossible due to ties
Six points on a line have positions 0, 1, 3, 7, 8 and 12. For each threshold hh, single linkage groups points connected by jumps of length at most hh. Of cluster counts k∈{1,2,3,4,5,6}k \in \{1, 2, 3, 4, 5, 6\}, how many cannot be obtained at any threshold hh?
QuizWeight transformations
Which graph-weight transformations always preserve the MST?

More than one answer may be correct.

QuizChoose the algorithm
Which algorithm choices are reasonable?

More than one answer may be correct.

ProofThe cut property
Prove: Let AA lie in some MST TT, (S,V∖S)(S, V \setminus S) be a cut respecting AA, and ee a light edge of that cut. Then A∪{e}A \cup \{e\} lies in some MST.
0
If e∈Te \in T there is nothing to prove. Assume e∉Te \notin T.

Step 1 of 4. What happens when ee is added to TT?

ProofDistinct weights give a unique MST
Prove: If all weights of a connected graph are distinct, the MST is unique.
0
Suppose TT and T′T' are distinct MSTs and consider their nonempty symmetric difference T △ T′T \,\triangle\, T'.

Step 1 of 4. Which edge do you choose?

CodeMinimum bottleneck spanning tree
Implement cuello_de_botella(n, aristas), where aristas lists tuples (u, v, w) of a connected graph with vertices 0..n-1. Return (b, arbol): arbol lists the indices of n−1n - 1 edges forming a spanning tree and b is its maximum edge weight, the smallest possible for any spanning tree. With n=1n = 1 return any value for b and arbol = []. Weights may tie; tests compare against enumeration of all trees on small graphs, minimum connectivity threshold on large graphs, and the maximum weight of a Kruskal MST.
def cuello_de_botella(n, aristas):
  """Devuelve (b, arbol): b = menor peso máximo posible, arbol = índices de n-1 aristas que lo alcanzan."""
  # tu código: ¿qué árbol sabes que ya minimiza el peso máximo?
  return None, []
Shift+Enter to run

Summary

Key idea
An MST is built by adding safe edges one at a time; the cut property identifies them: the lightest edge crossing any cut respected by the partial tree. Kruskal, Prim and Borůvka choose cuts in three ways.
  • Cut and cycle. A lightest edge of a cut respecting the partial tree is safe; a strictly heaviest cycle edge belongs to no MST. Distinct weights give a unique tree.
  • Kruskal sorts edges and accepts those joining distinct components (union-find), in O(mlog⁡n)\bigO(m \log n) dominated by sorting. Prim grows a tree with an indexed priority queue in O(mlog⁡n)\bigO(m \log n), O(m+nlog⁡n)\bigO(m + n \log n) with Fibonacci or O(n2)\bigO(n^2) with an array on dense graphs. Borůvka runs O(log⁡n)\bigO(\log n) phases with many independent choices and is naturally parallel.
  • Prim is not Dijkstra. Prim’s key is one edge weight, Dijkstra’s an accumulated distance. Their trees differ: an MST does not contain shortest paths.
  • Ties. Repeated weights require a total tie-break in Borůvka. The tree ceases to be unique, but all MSTs share their weight multiset.
  • Variants. The tree depends only on weight order (adding constants, squaring positive weights or logarithms preserve it; −w-w yields the maximum). Every MST minimizes maximum weight and its paths are minimax paths.
  • Linear time. Karger, Klein and Tarjan combine two Borůvka phases, edge sampling and forest-based heavy-edge filtering for expected O(m)\bigO(m). The sampling lemma, with (n−1)/p(n - 1)/p expected light edges, is key.
  • Applications. Single linkage is Kruskal cut at a height (with minimax-path ultrametric), Chow–Liu is a maximum tree on mutual information, and MST preorder gives a 2-approximation for metric traveling salesperson.