Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

ALGORITHMS · 12  /  KRUSKAL'S MST

The Cheapest Grid.

Eight towns, a price on every possible cable. Connect them all for the least total cost by always laying the cheapest cable that doesn't close a loop — and let Union-Find catch the loops for you.

THE GIST · 20 SECONDS

Kruskal's algorithm finds a minimum spanning tree — the cheapest set of edges that connects every node with no cycles. It's greedy: sort all edges by weight, then walk from cheapest to dearest, adding each edge unless it would form a cycle. A Union-Find answers "already connected?" in near-constant time. Stop at n − 1 edges — done.

  • MSTcheapest cycle-free connect
  • Greedyalways take the cheapest
  • Cyclea loop — reject it
  • Union-Find"already connected?"

Hit Step to weigh the next cheapest cable — or Play and watch the grid wire itself up for the least total cost.

UNDER THE HOOD

What you just played, written down

Sort once, then be greedy: take the cheapest edge that keeps the pieces separate. A Union-Find turns "would this close a loop?" into a constant-time check.

How Kruskal's thinks — four moves

  1. Sort every edge by weight. Cheapest first. This one sort is where all the cost goes.
  2. Start with n islands. Each node is its own component in a Union-Find — nothing connected yet.
  3. Take it if it merges two islands. For each edge in order, if its endpoints are in different components, add it and union them.
  4. Skip it if it's a loop. If the endpoints already share a leader, the edge would form a cycle — reject it and move on.
WHY GREEDY IS ACTUALLY OPTIMAL

The cut property: for any way you split the nodes into two groups, the cheapest edge crossing that split is safe to include in some MST. Kruskal always adds the cheapest edge joining two separate pieces — exactly such a safe edge.

The whole thing in code

def kruskal(n, edges):        # edges: [u, v, w]
    edges.sort(key=lambda e: e[2])   # cheapest first
    parent = list(range(n))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    total = 0
    for u, v, w in edges:
        ru, rv = find(u), find(v)
        if ru != rv:              # different islands?
            parent[ru] = rv       # union - take the edge
            total += w
        # else: same island -> cycle -> skip
    return total
TIMEO(E log E)dominated by the sort
SPACEO(V)the Union-Find
THE UNION-FIND IS THE WHOLE TRICK

Without it, checking "does this edge form a cycle?" means a graph search each time. Union-Find does it in O(α) — effectively constant — so the algorithm's cost collapses to just the initial sort.

⚠ Needs a connected graph

If the graph is disconnected, Kruskal's can't produce a single spanning tree — it builds a minimum spanning forest instead, one tree per connected component.

↔ Kruskal vs Prim

Kruskal sorts all edges and merges a forest (great for sparse graphs / edge lists). Prim grows one tree from a start node with a priority queue (often better for dense graphs).

★ Where it's used

Laying cable, roads, and pipelines for least cost, network design, clustering (cut the most expensive MST edges), and approximate solutions to harder tour problems.

The picture: the sorted list does the work

BC17BD26EG25AC34FG33AB43CD43FH42CE51GH5DF6BE6DE7EF8 groups left after each cable (8 at the start) stop: 1 group, 7 cables taken
The page’s 14 cables in cost order. Accent boxes were taken, dashed boxes were rejected as loops, plain boxes were never reached because the tree was already complete. The row of numbers under the first nine is how many separate groups of towns remain.

Worked example, step by step

Use the page’s eight towns A–H and fourteen cables. Edges of equal cost keep their input order (a stable sort). Each row is one cable examined in cost order; “groups” is the number of connected pieces left, starting from 8 single towns.

#CableCostDecisionGroupsTotal
1BC1take71
2BD2take63
3EG2take55
4AC3take48
5FG3take311
6AB4skip: same group311
7CD4skip: same group311
8FH4take215
9CE5take120

The tree costs 20 and uses 7 cables, one fewer than the 8 towns. Two decisions are worth reading closely. AB at 4 is rejected even though it is cheap: A joined the group through AC and B through BC, so A and B were already connected and the cable would close the loop A–B–C. CD at 4 is rejected for the same reason, since BD already joins D to the group. The algorithm then stops at row 9, when the group count reaches 1. The last five cables, the dearest ones, are never examined. With ties, a different order could pick a different tree, but never a different total.

Complexity and trade-offs

CaseTimeSpaceWhy
Kruskal, sort all edgesO(E log E)O(V) plus the edge listThe sort dominates. The union-find part is nearly linear.
Kruskal, heap instead of sortO(E + k log E)O(E)Heapify in linear time, then pop only as far as needed. On a 100-town complete graph (4,950 cables, random costs) the tree was finished after 211 cables; on a 1,000-town sparse graph (4,995 cables) after 3,238.
Prim, binary heapO(E log V)O(V)Grows one tree; no sort and no union-find.
Prim, arrayO(V²)O(V)Best on dense graphs.
BorůvkaO(E log V)O(V)Every component picks its cheapest edge each round; the components at least halve, so there are at most log V rounds. Easy to parallelise.

Union-find is why the sort stays the whole story. Without path compression, building a 1,000-town chain and then asking for the root of town 0 a thousand times costs 999,000 parent hops; with it, 1,998. Kruskal fits when the input is already an edge list or the graph is sparse. When the graph is dense, or the edges would have to be generated, Prim’s array version avoids sorting E edges.

Common mistakes

  • Taking the cheapest n − 1 edges without a cycle check

    On 4 towns with [[0,1,1],[1,2,1],[0,2,1],[2,3,5]] the three cheapest cables all cost 1, total 3, but they form a triangle and town 3 is unconnected. The real tree costs 7.

  • Attaching the vertex instead of its root

    The union must link the two roots, parent[find(u)] = find(v). Writing parent[u] = v detaches u from its old group. On [[0,3,6],[1,2,6],[1,3,6],[2,3,6]] it returns 24 where the answer is 18.

  • A recursive find on a deep chain

    A plain recursive find with no compression recurses once per link. A 2,000-town chain raises RecursionError under Python’s default limit of 1,000. Use an iterative find with path compression, and union by size or rank.

  • Ignoring disconnected input

    For 4 towns and cables [[0,1,2],[2,3,5]] the loop finishes with total 7 and only 2 cables. That is a forest, not a spanning tree. Check that exactly n − 1 cables were taken.

Where this shows up

  • Network and utility layout

    Cabling, pipelines and road links between fixed sites, where each possible link has a known cost, is the classic spanning-tree problem. Kruskal suits it because the candidate links arrive as a list.

  • Clustering

    Stop Kruskal when k groups are left, and you have single-linkage clustering into k clusters. The cables you did not add are the most expensive ones between groups.

  • Connectivity bookkeeping

    The union-find structure is useful by itself. It tracks which items are in the same group as links arrive, in nearly constant time per link, for example when merging accounts or detecting a loop as edges stream in.

  • Approximating tours

    In a graph whose costs obey the triangle inequality, doubling an MST and shortcutting repeated visits gives a tour at most twice the optimum.

SOLVE IT YOURSELF

Solve it: minimum spanning tree weight

This one is yours to write — in Python or TypeScript, running for real in your browser. Sort the edges, union the cheapest that don't form a cycle, and return the total weight. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement kruskal(n, edges): n nodes (0…n-1) and edges as [u, v, w] triples. Return the total weight of a minimum spanning tree using Kruskal's algorithm (assume the graph is connected).

HINTS — 4 IDEAS
  1. Sort the edges by weight ascending — the whole algorithm hinges on this order.
  2. Keep a Union-Find: parent[i] = i, and find(x) walks to the root (with path compression).
  3. For each edge, if find(u) != find(v), union them and add w to the total.
  4. If they're already in the same set, the edge is a cycle — skip it.
CPython · WebAssembly
QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. In what order does Kruskal’s algorithm consider the edges?

    Answer: From cheapest weight to most expensive — Kruskal sorts every edge by weight ascending and walks that list. Being greedy on the globally cheapest available edge is what makes the result a minimum spanning tree.

  2. Why does Kruskal’s reject some edges?

    Answer: Both endpoints are already connected, so the edge would form a cycle — A spanning tree has no cycles. If an edge’s endpoints already share a Union-Find leader they’re connected, so adding it would close a loop — Kruskal skips it.

  3. What dominates Kruskal’s O(E log E) running time?

    Answer: Sorting the edges — Union-Find operations are near-constant (O(α)), so sorting the E edges is the expensive part — O(E log E), which equals O(E log V).

FAQ

Kruskal's, answered

What is Kruskal's algorithm?

A greedy way to build a minimum spanning tree: sort every edge by weight, then add each cheapest edge unless it forms a cycle. After n − 1 edges, all nodes are connected for the least total weight.

What is a minimum spanning tree?

A subset of edges that connects all n nodes with exactly n − 1 edges and no cycles, at the smallest possible total weight — the cheapest way to wire everything together.

How does it use Union-Find?

Before adding an edge it checks find(u) == find(v). Equal leaders mean the two are already connected, so the edge would close a cycle and is skipped; otherwise union merges them and the edge joins the tree.

What's the time complexity?

O(E log E), dominated by sorting the edges. The Union-Find work across all edges is only O(E · α(V)) — effectively linear.

Kruskal vs Prim?

Both are greedy MST algorithms. Kruskal sorts all edges and merges a forest (good for sparse graphs); Prim grows one tree from a start node with a priority queue (good for dense graphs).

RESULT

—

Next → that cycle check you kept using is Union-Find, and growing one tree instead of a forest is Prim's algorithm. Same goal, different greedy.

Finished this one? 0 / 99 Algorithms done
NextGrow the Cheapest Tree: Prim’s MST Next on the “What is connected to what” ladder · rung 3 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms