Free explainer · Video · Code · Quiz
Kruskal's Algorithm
Build a minimum spanning tree by scanning edges from lightest to heaviest and keeping each one that does not close a cycle, checked with a union-find. Spanning forests, tie-breaking, and why the sort dominates the cost.
- Difficulty
- Medium
- Time
- O(E log E)
- Space
- O(V + E)
Try it yourself
Step through it at your own pace — this is Kruskal Animation, running right on the page.
LiveKruskal Animation
Loading the preview…
How it works
The idea, a worked example, and the traps to avoid.
The idea
You have to connect a set of villages with roads. Every possible road has a price, and you want everyone reachable from everyone else for the least total money. The answer is a minimum spanning tree (MST): a set of edges that connects every vertex, contains no cycle, and has the smallest possible total weight.
Kruskal's algorithm is the greedy answer. Sort all the edges from cheapest to most expensive. Walk through them, and build a road whenever it joins two places that are not connected yet. If the two ends are already connected, the road would only close a loop, so skip it. Nothing is ever undone: every edge that is kept stays in the tree.
The only hard question is "are these two ends already connected?", and it has to be answered once per edge. That is exactly what a disjoint set (union-find) is for. Every vertex starts in a group of its own. union(u, v) merges the two groups and returns false if u and v were already in the same one. Merging groups and asking the question are a single call.
Walkthrough
An undirected graph with seven vertices A to G (numbered 0 to 6): A–B (7), A–D (5), B–C (8), B–D (9), B–E (7), C–E (5), D–E (15), D–F (6), E–F (8), E–G (9), F–G (11).
First sort by weight. Edges of equal weight stay in the order they were given: A–D, C–E (5), D–F (6), A–B, B–E (7), B–C, E–F (8), B–D, E–G (9), F–G (11), D–E (15). Then:
| Step | Edge | Groups before | Decision |
|---|---|---|---|
| 1 | A–D (5) | A, D apart | Keep. {A, D} |
| 2 | C–E (5) | C, E apart | Keep. {C, E} |
| 3 | D–F (6) | D, F apart | Keep. {A, D, F} |
| 4 | A–B (7) | A, B apart | Keep. {A, B, D, F} |
| 5 | B–E (7) | B, E in different groups | Keep. {A, B, C, D, E, F} |
| 6 | B–C (8) | B, C already together | Skip: it would close a cycle |
| 7 | E–F (8) | E, F already together | Skip |
| 8 | B–D (9) | B, D already together | Skip |
| 9 | E–G (9) | E, G apart | Keep. One group is left |
Total weight: 5 + 5 + 6 + 7 + 7 + 9 = 39. Two edges, F–G (11) and D–E (15), are never looked at. Once only one group is left, every remaining edge would close a cycle, so the loop stops early. A tree on V vertices has exactly V − 1 edges, and here that is six.
The disjoint set
The set is a forest of trees, and each tree's root is the name of its group. find(x) climbs from x to its root. Two vertices are connected exactly when their roots are equal. Two small tricks keep the trees almost flat:
- Union by rank.
rankis an upper bound on a tree's height. When two groups merge, the shorter tree goes under the root of the taller one, so the height only grows when two trees of the same height meet. - Path compression. While
findclimbs, it points every vertex it passes straight at the root, so the nextfindfrom any of them takes one step.
Together they make each operation O(α(V)) amortized, where α is the inverse Ackermann function. It never passes 4 for any input that fits in a computer. Treat it as constant. The union-find page on this site covers the structure on its own.
Why it's correct
Claim: if Kruskal keeps an edge, some minimum spanning tree contains it, together with everything kept so far.
Say the edge e joins two different groups, and take the group S of one end. Any edge leaving S that is lighter than e would already have been examined, and it would have joined S to another group. None did, so e is a lightest edge leaving S. Take any MST T that contains the edges kept so far. If e is not in T, adding it makes a cycle, and that cycle must cross out of S through some other edge f. f is not lighter than e, so swapping f for e gives a tree that costs no more. It still contains everything kept so far, plus e. By induction the finished tree is minimal.
The same argument works for skipped edges: an edge that closes a cycle is no lighter than any other edge on that cycle (they were all examined first), and an edge that is a heaviest on its cycle can always be left out of an MST.
Not connected, ties, and odd edges
- Disconnected graph. There is no tree that spans everything, so the listing returns a minimum spanning forest: one MST per connected piece.
componentssays how many pieces there are, and the tree has V −componentsedges. Whencomponentsis 1, the graph is connected and the forest is a real MST. - Equal weights. An MST is often not unique: a triangle with three equal edges has three. The listing is deterministic anyway: the sort is stable, so equal edges stay in input order and the earlier one wins. All four languages print the same edges.
- Self-loops and parallel edges. A self-loop
u–ualways findsualready connected to itself and is skipped. Of two parallel edges, the lighter is examined first. - Negative weights. They are fine. Only the order matters, never the sign. This is a real advantage over Dijkstra.
- Single vertex, no edges. The result is an empty tree of weight 0, with
components1 (or the vertex count, when there are several vertices and no edges at all).
Complexity
Sorting E edges costs O(E log E). The loop then makes at most E union calls, each O(α(V)), so O(E α(V)) in total. Sorting dominates, so the whole algorithm is O(E log E). Since E ≤ V², log E ≤ 2 log V, which makes it the same as O(E log V). Space is O(V + E): the sorted copy of the edges, the disjoint set, and the tree.
If the edges arrive already sorted (or the weights are small integers and you can use a counting sort), the cost drops to O(E α(V)), almost linear.
Common bugs
- Testing connectivity with parents instead of roots.
parent[u] == parent[v]is not the same as "same group". Comparefind(u)withfind(v). - Forgetting that
sortmay not be stable, or may sort numbers as text. Equal weights then come out in a different order on each platform, and so does the tree. Use a stable sort with a numeric comparator. - Overflow. The total of int weights can pass 2³¹. Keep it in a
longorlong long. - Assuming the result is a tree. If the graph is not connected, you get a forest. Check
components. - Directed graphs. MST is about undirected graphs. For a directed graph, the equivalent problem is a minimum arborescence (Chu-Liu/Edmonds), and Kruskal does not solve it.
- Out-of-range vertices. Edges that name a vertex outside 0..V−1 index out of bounds in the disjoint set. Validate the input first.
When to use it (and when not)
Use it when the graph comes as an edge list and is sparse: network cabling, clustering (stop as soon as k groups are left to get k clusters), approximate solutions to the travelling salesman problem, image segmentation, building a maze. It is also the natural choice when you need the edges in order of weight anyway.
Prim's algorithm grows one tree from a starting vertex with a priority queue. It is often better on dense graphs stored as an adjacency matrix, where it runs in O(V²) with no sorting. Both give a minimum total weight.
Interview variations
- Connecting cities with minimum cost. Run Kruskal. If fewer than V − 1 edges were kept, return −1: the graph cannot be connected.
- Maximum spanning tree. Sort the edges from heaviest to lightest, or negate every weight, and run the same loop.
- Second-best MST, or "is this edge in every MST?". Build the MST, then for each non-tree edge look at the heaviest edge on the tree path between its ends. An edge belongs to every MST only if no other edge can replace it.
- Minimum cost to connect points (the points are vertices, the distances are weights). Generate all pairs and run Kruskal, or use Prim to avoid sorting O(V²) edges.
- Critical and pseudo-critical edges. For each edge, run Kruskal once with it forced in and once with it banned, and compare the weights with the plain MST.
Code
The same algorithm, step for step, in 4 languages.
// Kruskal's algorithm: the minimum spanning tree of a weighted, undirected graph — the cheapest set
// of edges that keeps every vertex connected. Look at the edges from lightest to heaviest and keep an
// edge unless it closes a cycle among the edges already kept. A disjoint set answers "would it?"
// in near-constant time. On a graph that is not connected the result is a spanning forest: one
// minimum tree per connected piece.
/** @typedef {[u: number, v: number, weight: number]} Edge an undirected edge between u and v (the weight may be negative) */
/**
* A disjoint set (union-find) over the vertices 0..n-1: every vertex starts in a group of its own,
* and groups only ever merge. Each group is a tree whose root is its name.
*/
class DisjointSet {
/** parent[x]: the next vertex up x's tree. A root is its own parent. */
#parent;
/** rank[r]: an upper bound on the height of the tree rooted at r (only read at roots). */
#rank;
/** How many separate groups there are right now. */
#count;
/** @param {number} n the number of vertices */
constructor(n) {
this.#parent = Array.from({ length: n }, (_, x) => x);
this.#rank = new Array(n).fill(0);
this.#count = n;
}
/** The number of separate groups. */
get count() {
return this.#count;
}
/**
* The root of x's tree. Two vertices are in the same group exactly when their roots are equal.
* @param {number} x
*/
find(x) {
let root = x;
while (this.#parent[root] !== root) root = this.#parent[root];
// Path compression: point every vertex on the way straight at the root.
let node = x;
while (this.#parent[node] !== root) {
const next = this.#parent[node];
this.#parent[node] = root;
node = next;
}
return root;
}
/**
* Merges the groups of a and b.
* @param {number} a
* @param {number} b
* @returns {boolean} true if two groups became one, false if a and b were already together
*/
union(a, b) {
let high = this.find(a);
let low = this.find(b);
if (high === low) return false;
// Union by rank: hang the shorter tree under the root of the taller one. On a tie, b's root
// goes under a's root and the new root grows one level, so the result is deterministic.
if (this.#rank[high] < this.#rank[low]) [high, low] = [low, high];
this.#parent[low] = high;
if (this.#rank[high] === this.#rank[low]) this.#rank[high]++;
this.#count--;
return true;
}
}
/**
* Orders edges by weight. `Array.prototype.sort` is stable, so edges of equal weight stay in the
* order they were given — that is the tie-break, and it keeps the result deterministic.
* @param {Edge} a
* @param {Edge} b
*/
function byWeight(a, b) {
return a[2] - b[2];
}
/**
* The minimum spanning forest of an undirected graph.
*
* @param {number} vertexCount the number of vertices; they are named 0..vertexCount-1
* @param {Edge[]} edges the edges, in any order. Self-loops and parallel edges are fine.
* @returns {{ tree: Edge[], weight: number, components: number }}
* tree: the kept edges, in the order they were added;
* weight: their total weight;
* components: how many connected pieces the graph has (1 means `tree` spans every vertex)
*/
export function kruskal(vertexCount, edges) {
const groups = new DisjointSet(vertexCount);
const tree = [];
let weight = 0;
for (const edge of [...edges].sort(byWeight)) {
if (groups.count === 1) break; // already one tree: every edge left would close a cycle
const [u, v, w] = edge;
// The union both asks the question and acts on the answer: false means u and v were already
// connected, so this edge would close a cycle — skip it.
if (!groups.union(u, v)) continue;
tree.push(edge);
weight += w;
}
return { tree, weight, components: groups.count };
}
# Kruskal's algorithm: the minimum spanning tree of a weighted, undirected graph — the cheapest set
# of edges that keeps every vertex connected. Look at the edges from lightest to heaviest and keep an
# edge unless it closes a cycle among the edges already kept. A disjoint set answers "would it?"
# in near-constant time. On a graph that is not connected the result is a spanning forest: one
# minimum tree per connected piece.
from typing import List, Tuple
# An undirected edge (u, v, weight) between u and v. The weight may be negative.
Edge = Tuple[int, int, int]
class DisjointSet:
"""A disjoint set (union-find) over the vertices 0..n-1.
Every vertex starts in a group of its own, and groups only ever merge. Each group is a tree
whose root is its name.
"""
def __init__(self, n: int) -> None:
# _parent[x]: the next vertex up x's tree. A root is its own parent.
self._parent: List[int] = list(range(n))
# _rank[r]: an upper bound on the height of the tree rooted at r (only read at roots).
self._rank: List[int] = [0] * n
self._count = n
@property
def count(self) -> int:
"""The number of separate groups."""
return self._count
def find(self, x: int) -> int:
"""Return the root of x's tree. Two vertices are in the same group exactly when their roots are equal."""
root = x
while self._parent[root] != root:
root = self._parent[root]
# Path compression: point every vertex on the way straight at the root.
node = x
while self._parent[node] != root:
next_node = self._parent[node]
self._parent[node] = root
node = next_node
return root
def union(self, a: int, b: int) -> bool:
"""Merge the groups of a and b.
Return True if two groups became one, False if a and b were already together.
"""
high = self.find(a)
low = self.find(b)
if high == low:
return False
# Union by rank: hang the shorter tree under the root of the taller one. On a tie, b's root
# goes under a's root and the new root grows one level, so the result is deterministic.
if self._rank[high] < self._rank[low]:
high, low = low, high
self._parent[low] = high
if self._rank[high] == self._rank[low]:
self._rank[high] += 1
self._count -= 1
return True
def by_weight(edge: Edge) -> int:
"""The sort key. `sorted` is stable, so edges of equal weight stay in the order they were
given — that is the tie-break, and it keeps the result deterministic."""
return edge[2]
def kruskal(vertex_count: int, edges: List[Edge]) -> Tuple[List[Edge], int, int]:
"""Return (tree, weight, components) for the minimum spanning forest of an undirected graph.
vertex_count: the number of vertices; they are named 0..vertex_count-1.
edges: the edges, in any order. Self-loops and parallel edges are fine.
tree: the kept edges, in the order they were added.
weight: their total weight.
components: how many connected pieces the graph has (1 means `tree` spans every vertex).
"""
groups = DisjointSet(vertex_count)
tree: List[Edge] = []
weight = 0
for edge in sorted(edges, key=by_weight):
if groups.count == 1:
break # already one tree: every edge left would close a cycle
u, v, w = edge
# The union both asks the question and acts on the answer: False means u and v were already
# connected, so this edge would close a cycle — skip it.
if not groups.union(u, v):
continue
tree.append(edge)
weight += w
return tree, weight, groups.count
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* Kruskal's algorithm: the minimum spanning tree of a weighted, undirected graph — the cheapest set
* of edges that keeps every vertex connected. Look at the edges from lightest to heaviest and keep an
* edge unless it closes a cycle among the edges already kept. A disjoint set answers "would it?"
* in near-constant time. On a graph that is not connected the result is a spanning forest: one
* minimum tree per connected piece.
*/
public final class Kruskal {
/** An undirected edge between u and v. The weight may be negative. */
public record Edge(int u, int v, int weight) {
}
/**
* tree: the kept edges, in the order they were added.
* weight: their total weight.
* components: how many connected pieces the graph has (1 means the tree spans every vertex).
*/
public record Result(List<Edge> tree, long weight, int components) {
}
/** Orders edges by weight. {@code List.sort} is stable, so edges of equal weight stay in the
* order they were given — that is the tie-break, and it keeps the result deterministic. */
private static final Comparator<Edge> BY_WEIGHT = Comparator.comparingInt(Edge::weight);
private Kruskal() {
}
/**
* A disjoint set (union-find) over the vertices 0..n-1: every vertex starts in a group of its
* own, and groups only ever merge. Each group is a tree whose root is its name.
*/
private static final class DisjointSet {
/** parent[x]: the next vertex up x's tree. A root is its own parent. */
private final int[] parent;
/** rank[r]: an upper bound on the height of the tree rooted at r (only read at roots). */
private final int[] rank;
/** How many separate groups there are right now. */
private int count;
DisjointSet(int n) {
parent = new int[n];
for (int x = 0; x < n; x++) {
parent[x] = x;
}
rank = new int[n];
count = n;
}
int count() {
return count;
}
/** The root of x's tree. Two vertices are in the same group exactly when their roots are equal. */
int find(int x) {
int root = x;
while (parent[root] != root) {
root = parent[root];
}
// Path compression: point every vertex on the way straight at the root.
int node = x;
while (parent[node] != root) {
int next = parent[node];
parent[node] = root;
node = next;
}
return root;
}
/** Merges the groups of a and b. Returns true if two groups became one, false if a and b were already together. */
boolean union(int a, int b) {
int high = find(a);
int low = find(b);
if (high == low) {
return false;
}
// Union by rank: hang the shorter tree under the root of the taller one. On a tie, b's
// root goes under a's root and the new root grows one level, so the result is deterministic.
if (rank[high] < rank[low]) {
int swap = high;
high = low;
low = swap;
}
parent[low] = high;
if (rank[high] == rank[low]) {
rank[high]++;
}
count--;
return true;
}
}
/**
* The minimum spanning forest of an undirected graph with vertices 0..vertexCount-1.
* The edges may come in any order; self-loops and parallel edges are fine.
*/
public static Result kruskal(int vertexCount, List<Edge> edges) {
DisjointSet groups = new DisjointSet(vertexCount);
List<Edge> tree = new ArrayList<>();
long weight = 0; // long: sums of int weights can overflow int
List<Edge> sorted = new ArrayList<>(edges);
sorted.sort(BY_WEIGHT);
for (Edge edge : sorted) {
if (groups.count() == 1) {
break; // already one tree: every edge left would close a cycle
}
// The union both asks the question and acts on the answer: false means u and v were
// already connected, so this edge would close a cycle — skip it.
if (!groups.union(edge.u(), edge.v())) {
continue;
}
tree.add(edge);
weight += edge.weight();
}
return new Result(tree, weight, groups.count());
}
}
// Kruskal's algorithm: the minimum spanning tree of a weighted, undirected graph — the cheapest set
// of edges that keeps every vertex connected. Look at the edges from lightest to heaviest and keep an
// edge unless it closes a cycle among the edges already kept. A disjoint set answers "would it?"
// in near-constant time. On a graph that is not connected the result is a spanning forest: one
// minimum tree per connected piece.
#include <algorithm>
#include <numeric>
#include <utility>
#include <vector>
// An undirected edge between u and v. The weight may be negative.
struct Edge {
int u;
int v;
int weight;
};
// tree: the kept edges, in the order they were added.
// weight: their total weight.
// components: how many connected pieces the graph has (1 means the tree spans every vertex).
struct SpanningForest {
std::vector<Edge> tree;
long long weight;
int components;
};
// A disjoint set (union-find) over the vertices 0..n-1: every vertex starts in a group of its own,
// and groups only ever merge. Each group is a tree whose root is its name.
class DisjointSet {
public:
explicit DisjointSet(int n) : parent_(n), rank_(n, 0), count_(n) {
std::iota(parent_.begin(), parent_.end(), 0); // parent_[x] = x: everyone is a root
}
// The number of separate groups.
int count() const {
return count_;
}
// The root of x's tree. Two vertices are in the same group exactly when their roots are equal.
int find(int x) {
int root = x;
while (parent_[root] != root) {
root = parent_[root];
}
// Path compression: point every vertex on the way straight at the root.
int node = x;
while (parent_[node] != root) {
int next = parent_[node];
parent_[node] = root;
node = next;
}
return root;
}
// Merges the groups of a and b (named unite because `union` is a C++ keyword).
// Returns true if two groups became one, false if a and b were already together.
bool unite(int a, int b) {
int high = find(a);
int low = find(b);
if (high == low) {
return false;
}
// Union by rank: hang the shorter tree under the root of the taller one. On a tie, b's root
// goes under a's root and the new root grows one level, so the result is deterministic.
if (rank_[high] < rank_[low]) {
std::swap(high, low);
}
parent_[low] = high;
if (rank_[high] == rank_[low]) {
++rank_[high];
}
--count_;
return true;
}
private:
std::vector<int> parent_; // parent_[x]: the next vertex up x's tree; a root is its own parent
std::vector<int> rank_; // rank_[r]: an upper bound on the height of the tree rooted at r (only read at roots)
int count_; // how many separate groups there are right now
};
// Orders edges by weight. The sort is stable, so edges of equal weight stay in the order they were
// given — that is the tie-break, and it keeps the result deterministic.
static bool byWeight(const Edge& a, const Edge& b) {
return a.weight < b.weight;
}
// The minimum spanning forest of an undirected graph with vertices 0..vertexCount-1.
// The edges may come in any order; self-loops and parallel edges are fine.
SpanningForest kruskal(int vertexCount, std::vector<Edge> edges) {
DisjointSet groups(vertexCount);
SpanningForest result{{}, 0, vertexCount}; // long long: sums of int weights can overflow int
std::stable_sort(edges.begin(), edges.end(), byWeight);
for (const Edge& edge : edges) {
if (groups.count() == 1) {
break; // already one tree: every edge left would close a cycle
}
// The union both asks the question and acts on the answer: false means u and v were already
// connected, so this edge would close a cycle — skip it.
if (!groups.unite(edge.u, edge.v)) {
continue;
}
result.tree.push_back(edge);
result.weight += edge.weight;
}
result.components = groups.count();
return result;
}
Test yourself
10 quick questions to check it stuck.
Q1 · An undirected graph with vertices 0 to 6 and these edges (u–v, weight): 0–1 (7), 0–3 (5), 1–2 (8), 1–3 (9), 1–4 (7), 2–4 (5), 3–4 (15), 3–5 (6), 4–5 (8), 4–6 (9), 5–6 (11). What is weight after kruskal(7, edges)?
Take it further
- Animation
Kruskal Animation
A glowing graph where the cheapest network builds itself: Kruskal's minimum spanning tree with a sorted edge list and union-find colours, for lessons and slides
Free
