AlgoViz

Kruskal's algorithm

medium 20 min

Kruskal's algorithm finds a minimum spanning tree: the cheapest set of edges that connects every vertex with no cycles.

Video lesson · Chapter 1 of 7

Bridge auction

0:00 / 4:08

Kruskal's algorithm in 75 seconds

1:25Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Sort every edge by weight. One O(E log E) sort puts the cheapest edge first; this is the main cost of the algorithm

Understand it

Start here

What a minimum spanning tree is

Quick recap

  • Weighted graph

    Vertices joined by edges, each with a cost w(e)w(e). Basics in graphs intro.

  • Tree

    Connected and acyclic. On VV vertices it always has exactly V−1V - 1 edges.

  • Spanning

    It touches every vertex of the graph, using only the graph's own edges.

  • Minimum

    Of all spanning trees, the one whose edge weights add up to the least.

The goal

T∗=arg⁡min⁡T spanning tree of G  ∑e∈Tw(e),∣T∗∣=V−1T^{*} = \arg\min_{T \,\text{spanning tree of}\, G} \; \sum_{e \in T} w(e), \qquad |T^{*}| = V - 1
A connected, undirected, weighted graph always has at least one MST. If all weights are distinct it has exactly one; with ties there may be several, all with the same total.

Picture islands and the bridges you could build between them, each with a price. You want every island reachable from every other for the least money. Any loop of bridges wastes money, since one bridge in the loop could be dropped and everything stays connected. So the answer is a tree, and the cheapest such tree is the minimum spanning tree.

The idea

Cheapest edge first, skip any cycle

Kruskal's algorithm is greedy and edge-centric. It never grows from a start vertex. Instead it keeps a forest of fragments, starting with every vertex alone, and repeatedly takes the cheapest remaining edge. If that edge joins two different fragments, it goes in and the fragments merge. If both ends are already in the same fragment, the edge would close a loop, so it is skipped.

The SAFE loop
  1. 1SortAll edges by weight, O(E log E)
  2. 2Findfind(u) and find(v): which components?
  3. 3Add or skipDifferent roots: add and union. Same root: skip
  4. 4Enough?Stop at V - 1 edges
Repeat: back to Sort

Sort, Add if no cycle, Find components, Edge accepted or rejected: SAFE.

Kruskal's algorithm

Only two outcomes per edge. Every accepted edge reduces the number of components by one, so after V−1V - 1 accepts there is one tree.

Step 1

Sort the edges

The simple graph, sorted

OrderEdgeWeightVerdict
1B-C1accept
2E-F1accept
3B-D2accept
4D-E2accept, merges {B, C, D} with {E, F}
5A-C3accept, 5 = V - 1 edges: stop
6 to 9A-B, C-D, C-E, D-F4, 4, 5, 6never examined
Total weight 1+1+2+2+3=91 + 1 + 2 + 2 + 3 = 9. Ties (B-C and E-F) can go in either order; the total is the same.

Sorting is the bottleneck

Tsort=O(Elog⁡E),Tloop=O(E⋅α(V))≈O(E)T_{\text{sort}} = O(E \log E), \qquad T_{\text{loop}} = O\big(E \cdot \alpha(V)\big) \approx O(E)
Python's sorted(edges, key=lambda e: e[2]) is a stable O(Elog⁡E)O(E \log E) sort. Everything after it is nearly linear, so the sort sets the running time.

Step 2

The cycle check with union-find

An edge (u,v)(u, v) closes a cycle exactly when uu and vv are already connected by chosen edges. Union-find (disjoint set union) tracks the components: every set has one root, find(x) returns x's root, and union(a, b) merges two sets by pointing one root at the other.

  • find(x)

    Follow parent pointers to the root of x's set. Same root means same component. O(α(n))O(\alpha(n)) amortised.

  • union(a, b)

    Link the root of one set under the root of the other. Returns False if they already shared a root. O(α(n))O(\alpha(n)) amortised.

Accept or reject: the roots decide

C and D are already joined through B, so a C-D edge would make the triangle B-C-D. D and E are in different sets, so D-E is a bridge between fragments.

Compare roots with find

  • Answers exactly the question that matters: are u and v already connected?
  • Near O(1)O(1) per edge with path compression and union by rank.
  • Works no matter how the fragments formed.

Shortcuts that break

  • "Both ends visited": rejects edges that join two different fragments.
  • Compare parent[u] and parent[v]: parents are only the next hop, not the root.
  • Run DFS to look for a path each time: correct but O(V)O(V) per edge, O(EV)O(EV) total.

Under the hood

Path compression and union by rank

A naive union-find can build a long chain, and then every find walks it. Two small tricks keep the trees almost flat. Path compression: after finding the root, point every vertex on the path straight at it. Union by rank: hang the shorter tree under the taller one, where rank is an upper bound on height.

find with path compression

In the visualizer's close-up, D → C → A becomes D → A after one find.

Cost per operation

O(n)⏟naive chain  →  O(log⁡n)⏟rank or compression alone  →  O(α(n))⏟both, amortised,α(n)≤4 for any practical n\underbrace{O(n)}_{\text{naive chain}} \;\to\; \underbrace{O(\log n)}_{\text{rank or compression alone}} \;\to\; \underbrace{O(\alpha(n))}_{\text{both, amortised}}, \qquad \alpha(n) \le 4 \text{ for any practical } n
α\alpha is the inverse Ackermann function, which grows so slowly that it is a constant for every input that fits in memory.
Python
class DSU:    def __init__(self, items):        self.parent = {x: x for x in items}        self.rank = {x: 0 for x in items}    def find(self, x):        if self.parent[x] != x:            self.parent[x] = self.find(self.parent[x])   # path compression        return self.parent[x]    def union(self, a, b):        ra, rb = self.find(a), self.find(b)        if ra == rb:            return False                                 # already connected        if self.rank[ra] < self.rank[rb]:            ra, rb = rb, ra        self.parent[rb] = ra                             # union by rank        if self.rank[ra] == self.rank[rb]:            self.rank[ra] += 1        return Trued = DSU("ABCDE")print(d.union("A", "B"), d.union("C", "D"), d.union("B", "D"))  # True True Trueprint(d.union("A", "D"))                                       # False: cycleprint(d.find("D"), d.parent["D"])                              # A A (compressed)
Union-find with both tricks. union returns whether a merge happened, which is exactly Kruskal's accept test.
Edit and run it in your browser

Worked example

The computer network

Six machines, nine possible cables. Buying every cable costs 37. Kruskal picks the cheapest cables that still connect everyone.

  1. 1

    Sort

    3-4(1), 0-2(2), 4-5(2), 1-4(3), 0-1(4), 2-4(4), 1-2(5), 2-5(6), 1-3(10).

  2. 2

    3-4, 0-2, 4-5

    Each joins two different sets. Running total 1+2+2=51 + 2 + 2 = 5. Groups: {3, 4, 5} and {0, 2}, with 1 alone.

  3. 3

    1-4 (3)

    find(1) = 1, find(4) = 3: different. Accept, total 8. Groups: {1, 3, 4, 5} and {0, 2}.

  4. 4

    0-1 (4)

    find(0) = 0, find(1) = 3: different. Accept, total 12. That is 5 edges for 6 vertices: stop.

  5. 5

    What was skipped

    2-4, 1-2, 2-5 and 1-3 are never looked at. The cost-10 link is avoided because machine 3 is reached through 4 for 1.

Why it works

The cut property and the exchange argument

Cut property

For any cut (S, V∖S):e=arg⁡min⁡(x,y): x∈S, y∉Sw(x,y)  ⟹  e belongs to some MST\text{For any cut } (S,\, V \setminus S): \quad e = \arg\min_{(x,y):\, x \in S,\, y \notin S} w(x, y) \;\Longrightarrow\; e \text{ belongs to some MST}
A cut splits the vertices into two groups. If ee is the strictly lightest crossing edge, it is in every MST.

Exchange argument

Swap one edge for a no-heavier one and the tree stays minimal: that is the whole proof of the cut property.

The swap never costs more

w(T′)=w(T)+w(e)−w(f)≤w(T)since w(e)≤w(f)w(T') = w(T) + w(e) - w(f) \le w(T) \quad \text{since } w(e) \le w(f)
Applying it to Kruskal: when Kruskal accepts e=(u,v)e = (u, v), let SS be u's current component. No chosen edge crosses this cut, and every cheaper edge was either inside a component or already merged, so ee is the lightest edge crossing (S,V∖S)(S, V \setminus S). By the cut property it is safe, and by induction every accepted edge extends some MST.

Cost

Why O(E log E), and why that equals O(E log V)

Total running time

T(V,E)=O(V)⏟make sets+O(Elog⁡E)⏟sort+O(E α(V))⏟2E finds,  V−1 unions=O(Elog⁡E)T(V, E) = \underbrace{O(V)}_{\text{make sets}} + \underbrace{O(E \log E)}_{\text{sort}} + \underbrace{O(E\,\alpha(V))}_{2E \text{ finds},\; V-1 \text{ unions}} = O(E \log E)
Space is O(V+E)O(V + E): the edge list (and its sorted copy) plus the parent and rank arrays.

log E and log V are the same order

E≤(V2)<V2  ⇒  log⁡E<2log⁡V  ⇒  O(Elog⁡E)=O(Elog⁡V)E \le \binom{V}{2} < V^{2} \;\Rightarrow\; \log E < 2 \log V \;\Rightarrow\; O(E \log E) = O(E \log V)
Both forms are correct answers in an interview. For a connected graph E≥V−1E \ge V - 1, so the sort also dominates the O(V)O(V) setup.

Where the time goes

PhaseWorkCost
Make setsparent[v] = v, rank[v] = 0O(V)O(V)
Sort edgesComparison sort by weightO(Elog⁡E)O(E \log E)
Scan edgesUp to EE edges, 2 finds eachO(E α(V))O(E\,\alpha(V))
MergeExactly V−1V - 1 successful unionsO(V α(V))O(V\,\alpha(V))
With a naive union-find (no rank, no compression) the scan becomes O(EV)O(EV) and dominates instead.

Compared

Kruskal versus Prim

Prim's algorithm builds the same minimum tree from the other direction: start at any vertex and repeatedly add the cheapest edge leaving the tree, using a priority queue. Both are greedy, both rely on the cut property, and on a graph with distinct weights both return the identical tree.

AspectKruskalPrim
ApproachEdge-centric: sort all edgesVertex-centric: grow one tree
Key structureUnion-findPriority queue
TimeO(Elog⁡E)O(E \log E)O((V+E)log⁡V)O((V + E) \log V) with a heap, O(V2)O(V^2) with an array
Best forSparse graphs, edge lists, pre-sorted edgesDense graphs, adjacency matrices
Midway stateA forest of fragmentsOne connected tree
Disconnected inputNaturally gives a spanning forestCovers one component per start
On a complete graph, E≈V2/2E \approx V^2/2: Kruskal pays O(V2log⁡V)O(V^2 \log V) to sort, while array-based Prim is O(V2)O(V^2).

Which one to reach for

In interviews, Kruskal is usually quicker to write correctly: a sort, a loop and a 15-line union-find.

In code

A complete implementation and its edge cases

Python
def kruskal_mst(n, edges):    parent = list(range(n))    rank = [0] * n    def find(x):        while parent[x] != x:            parent[x] = parent[parent[x]]    # path halving: iterative compression            x = parent[x]        return x    mst, total = [], 0    for u, v, w in sorted(edges, key=lambda e: e[2]):        ru, rv = find(u), find(v)        if ru == rv:            continue                         # would close a cycle        if rank[ru] < rank[rv]:            ru, rv = rv, ru        parent[rv] = ru        if rank[ru] == rank[rv]:            rank[ru] += 1        mst.append((u, v, w))        total += w        if len(mst) == n - 1:            break                            # tree complete    return (mst, total) if len(mst) == n - 1 or n <= 1 else Noneedges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4)]print(kruskal_mst(4, edges))                 # ([(1, 2, 1), (1, 3, 2), (0, 2, 3)], 6)print(kruskal_mst(4, [(0, 1, 1), (2, 3, 1)]))  # None: two separate components
Vertices 0..n-1, edges as (u, v, w). Returns the MST and its weight, or None if the graph is disconnected.
Edit and run it in your browser
  • Disconnected graph

    Edges run out with fewer than V−1V - 1 accepted. You have a minimum spanning forest of V−cV - c edges for cc components. Report it or return -1.

  • Equal weights

    Any tie order gives a valid MST with the same total. The tree itself may differ.

  • Negative weights

    Fine. Kruskal only compares weights, so negative edges need no special care, unlike Dijkstra.

  • Self-loops and parallel edges

    A self-loop has find(u) = find(v) and is rejected automatically. Of parallel edges, the cheapest is seen first.

Variations

Same loop, other questions

  • Maximum spanning tree

    Sort descending (or negate weights). Used for the widest-bandwidth backbone.

  • k clusters

    Stop when kk components remain. The next edge Kruskal would accept is the spacing between clusters, and it is the largest possible.

  • Critical edges

    An edge is critical if removing it raises the MST weight. Test it by rerunning Kruskal without it: O(E2α(V))O(E^2 \alpha(V)) for all edges.

  • Connect all points

    A complete graph of Manhattan or Euclidean distances: E=V(V−1)/2E = V(V-1)/2, so Prim's O(V2)O(V^2) often wins.

Single-link clustering with Kruskal

Stopping Kruskal early is exactly single-linkage hierarchical clustering cut at kk groups.

Recap

Key takeaways

Kruskal fits when

  • You need the cheapest way to connect everything: networks, roads, pipes, wiring.
  • The graph is given as a list of weighted edges, or is sparse.
  • Edges are already sorted, or weights are small integers.
  • You want clusters: stop early at kk components.

Look elsewhere when

  • You need shortest paths between vertices: use Dijkstra.
  • The graph is directed: use Chu-Liu/Edmonds.
  • The graph is dense or a full distance matrix: Prim's O(V2)O(V^2) is better.

Key points

  • An MST connects all VV vertices with V−1V - 1 edges of least total weight; it is unique when weights are distinct.
  • Kruskal: sort edges ascending, accept an edge when find(u) != find(v) and union them, stop at V−1V - 1 edges.
  • Union-find with path compression and union by rank makes each check O(α(V))O(\alpha(V)), effectively constant.
  • Time O(Elog⁡E)=O(Elog⁡V)O(E \log E) = O(E \log V), dominated by the sort; space O(V+E)O(V + E).
  • Correctness: each accepted edge is the lightest edge crossing the cut around its component, so the cut property makes it safe.
  • Prim grows one tree with a priority queue and suits dense graphs; Kruskal merges a forest and suits sparse edge lists.

Sources