Sub topic 14
Applications: Network Design and Single-Linkage Clustering
This chapter assumes you have read the earlier chapters on Kruskal's and Prim's algorithms and the disjoint-set structure. It also assumes you can read Python and know Big-O notation. It covers two common uses of minimum spanning trees. The first is building the cheapest network that connects every site. The second is grouping data points into clusters. For each one, you will see what the MST guarantees and where people misuse it.
Network Design: Connecting Sites at Minimum Total Cost
The MST problem first came from engineering. Otakar Borůvka studied it in 1926 while planning an electrical grid for Moravia. The setup is still common:
- Vertices are sites: houses, servers, towns, or oil wells.
- An edge is a possible link: a cable, a pipe, a fibre run, or a road.
- An edge's weight is the cost of building that link.
You want every site to reach every other site, and you want to pay as little as possible. A cycle always contains one edge you could remove without disconnecting anything, so the cheapest connected network never has a cycle. That makes it a spanning tree, and the cheapest spanning tree is the MST.
A Small Fibre-Network Example
Suppose a campus must connect five buildings with fibre. The table lists the cost of each possible trench, in thousands of dollars.
| Link | Cost |
|---|---|
| Library – Lab | 4 |
| Library – Dorm | 2 |
| Lab – Dorm | 5 |
| Lab – Gym | 3 |
| Dorm – Gym | 7 |
| Dorm – Admin | 6 |
| Gym – Admin | 1 |
Kruskal's algorithm takes edges in order of cost: Gym–Admin (1), Library–Dorm (2), Lab–Gym (3), Library–Lab (4). That gives four edges for five vertices, so the algorithm stops. The total is 10. The edges it never reached (Lab–Dorm at 5, Dorm–Admin at 6, Dorm–Gym at 7) would each have closed a cycle.
What the MST Does Not Optimize
The MST minimizes one thing: the sum of the edge weights. Real network requirements often go beyond that, and the MST then answers a different question from the one being asked.
| Requirement | Does the MST handle it? | What to use instead |
|---|---|---|
| Minimum total build cost | Yes | MST |
| Short path from a hub to every site | No. Tree paths can be long. | Shortest-path tree (Dijkstra) |
| Survive any single link failure | No. Every tree edge is a single point of failure. | 2-edge-connected network design |
| Add new junction points to cut cost | No. The MST uses only the given vertices. | Steiner tree (NP-hard; approximated) |
| Limit the number of links per site | No | Degree-constrained MST (NP-hard) |
In the campus example, a packet from Dorm to Admin travels Dorm → Library → Lab → Gym → Admin, which is four hops. The direct Dorm–Admin link would be one hop. The MST skipped it because it costs more than the links that already connect those buildings.
The Bottleneck Property
The MST does give one routing guarantee. For any two vertices, the path between them in the MST has the smallest possible maximum edge weight among all paths in the graph. This is called the minimax or bottleneck path.
This follows from the cycle property. Suppose some other path from u to v avoided an edge heavier than every edge on that path. Then that heavy MST edge would be the heaviest edge on a cycle, and it could not be in the MST.
It matters whenever the weakest link limits the whole route. A truck limited by the lowest bridge clearance wants to maximize the minimum clearance along its route, so you run the MST with reversed weights (a maximum spanning tree). The same idea applies to bandwidth, where the slowest link sets the throughput.
MSTs Inside Approximation Algorithms
MSTs also serve as building blocks for harder problems. For the travelling salesman problem with distances that obey the triangle inequality, a classic method builds the MST, walks around it in depth-first order, and skips repeated vertices. The resulting tour costs at most twice the optimum. Removing one edge from any tour gives a spanning tree, so the optimal tour costs at least as much as the MST. Christofides' algorithm builds on the same idea and reaches a factor of 1.5.
Single-Linkage Clustering
Clustering divides points into groups so that points in a group are close together and groups are far apart. Single-linkage clustering measures the distance between two clusters by their closest pair of points. It then repeatedly merges the two closest clusters.
That merge loop is Kruskal's algorithm. Treat each point as a vertex, connect every pair with an edge weighted by distance, and process the edges in sorted order. Each successful union merges two clusters. If you stop when k components remain, you have k clusters.
Stopping early is equivalent to building the full MST and deleting its k − 1 heaviest edges.
What Single Linkage Guarantees
Define the spacing of a clustering as the smallest distance between two points in different clusters. Among all ways to split the points into k groups, the Kruskal-stopped clustering has the largest possible spacing.
The proof sketch: let d be the weight of the next MST edge Kruskal would have added. Any other k-clustering must separate two points that are in the same Kruskal cluster. The path between those two points uses only edges of weight at most d. Somewhere along that path, one edge crosses between the other clustering's groups, so that clustering's spacing is at most d*.
Implementation
The code below is self-contained. It repeats the DisjointSet class from the union-find chapter so you can run it on its own.
import math
from itertools import combinations
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
def single_linkage(points, k):
"""Split points into k clusters; return (clusters, spacing)."""
n = len(points)
if not 1 <= k <= n:
raise ValueError("k must be between 1 and the number of points")
edges = sorted(
(math.dist(points[i], points[j]), i, j)
for i, j in combinations(range(n), 2)
)
ds = DisjointSet(n)
components = n
spacing = None
for w, u, v in edges:
if ds.find(u) == ds.find(v):
continue # same cluster already; edge adds nothing
if components == k:
spacing = w # first edge that would join two final clusters
break
ds.union(u, v)
components -= 1
groups = {}
for i in range(n):
groups.setdefault(ds.find(i), []).append(i)
return list(groups.values()), spacing
names = ["A", "B", "C", "D", "E", "F"]
points = [(0, 0), (1, 0), (0, 1), (5, 5), (6, 5), (10, 0)]
clusters, spacing = single_linkage(points, 3)
for c in clusters:
print([names[i] for i in c])
print(round(spacing, 3))
# ['A', 'B', 'C']
# ['D', 'E']
# ['F']
# 6.403To trace it, note that the three edges of length 1 (A–B, A–C, D–E) come first and reduce the six components to three. B–C, at about 1.414, would join two points already in the same cluster, so the loop skips it. The next edge is B–D at √41 ≈ 6.403. Three components remain, so the loop records that distance as the spacing and stops. F stays on its own because its nearest neighbour, E, is also √41 away.
Costs and Practical Notes
The input is a complete graph, so E = n(n − 1)/2. Sorting all those edges costs O(n² log n) time and O(n²) memory. For a few thousand points this is fine. For larger inputs:
- Prim's algorithm with an array instead of a heap runs in O(n²) time and needs only O(n) extra memory if it computes distances on the fly. It is the better choice for dense complete graphs, as the complexity chapter explained.
- For points in the plane, the Euclidean MST is a subgraph of the Delaunay triangulation, which has O(n) edges. Running Kruskal on those edges gives O(n log n) in total.
- Libraries such as SciPy (
scipy.cluster.hierarchy.linkagewithmethod="single") use MST-based algorithms and return the full merge history, called a dendrogram. You can cut the dendrogram at any k without recomputing.
Common Errors
- Stopping by threshold versus by count. Cutting every MST edge heavier than a distance t gives a different number of clusters than asking for k. Pick the option that fits the problem, and say which one you used.
- Mixing feature scales. Euclidean distance on raw features lets the feature with the largest units dominate. Normalize the features first.
- Ties at the cut. If several edges share the weight at the cut point, the k-clustering may not be unique. This is the same condition that makes the MST non-unique.
Choosing the Right Model
Before you reach for an MST, check what the problem actually asks for:
- If you need everything connected at minimum total weight, use an MST.
- If the weakest link on a route limits the result, use an MST or a maximum spanning tree for bottleneck paths.
- If you need groups with the widest separation, use an MST with its k − 1 heaviest edges removed.
- If the requirement involves path lengths, redundancy, or extra junction points, the MST is at most a starting heuristic.
Exercise
In the campus example, the university wants a building pair that is connected only through Gym to keep its connection if any single trench is cut. Can the MST provide this? What is the cheapest single trench you could add to the MST so that Admin no longer depends on the Gym–Admin link alone?
Show answer
No. Every edge in a tree is a bridge, so cutting Gym–Admin disconnects Admin. To give Admin a second route, add an edge that touches Admin. Dorm–Admin (cost 6) is the only such link left, so the network costs 16 in total. It creates the cycle Admin–Dorm–Library–Lab–Gym–Admin, so no single trench cut on that cycle can isolate Admin.
Exercise
Run single_linkage(points, 2) on the six example points. Which clusters do you get, and what is the spacing?
Show answer
The clusters are ['A', 'B', 'C', 'D', 'E'] and ['F']. After the length-1 edges, B–D (√41) merges the first two clusters, leaving two components. The next edge, C–D, also has length √41 but joins vertices already in the same cluster, so the loop skips it. E–F (√41) then crosses between the two final clusters, so the spacing is about 6.403. This tie means the 3-cluster and 2-cluster cuts have the same spacing.
Exercise
Why does the MST path between two vertices minimize the maximum edge weight among all paths between them? Answer in two or three sentences using the cycle property.
Show answer
Suppose the MST path from u to v contains an edge e that is heavier than every edge on some other u–v path P. Then e together with P and the rest of the tree path forms a cycle in which e is strictly the heaviest edge. By the cycle property, e cannot be in any MST, which is a contradiction.