Tiem Cong Nghe

Showing suggestions.

Opening the store's index…
↑↓ to move↵ to openesc to close
Tiem Cong Nghe search

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.

Get this code

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. rank is 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 find climbs, it points every vertex it passes straight at the root, so the next find from 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. components says how many pieces there are, and the tree has V − components edges. When components is 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–u always finds u already 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 components 1 (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". Compare find(u) with find(v).
  • Forgetting that sort may 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 long or long 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

  1. Connecting cities with minimum cost. Run Kruskal. If fewer than V − 1 edges were kept, return −1: the graph cannot be connected.
  2. Maximum spanning tree. Sort the edges from heaviest to lightest, or negate every weight, and run the same loop.
  3. 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.
  4. 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.
  5. 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.

JavaScript
// 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 };
}

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 the quiz

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