AlgoTales · Roadmap

Kruskal's algorithm

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Kruskal's algorithm also finds the cheapest way to connect everything, but it works over all links at once: sort them by cost and keep each one unless it would close a loop. It is the favourite when links arrive as a simple list.

Practical use cases

  • Web app: Village road budget tool. A government or NGO portal lists possible roads between villages with their costs. Sorting them cheapest-first and accepting each road that joins two not-yet-connected groups produces the cheapest plan, and the screen shows the total saved against the full list.
  • Web app: Customer clustering report. A marketing dashboard treats customers as points with a similarity distance. Adding the closest pairs first and stopping when 5 groups remain gives 5 customer segments, a simple form of clustering.
  • Web app: CSV of links to cheapest plan. An admin uploads a CSV with from, to and cost columns. Since the data is already an edge list, the backend sorts the rows once and loops through them to return the chosen links as JSON, with no extra data shapes.
  • System: Power grids and cabling. Utilities use the same idea to plan which lines to build so every area is powered at the lowest total cost. The method scales well because sorting the list once is the only expensive step, and after that each link is a quick yes or no.

The story: The Sarpanch and the Cheapest Roads

The sarpanch of a small block called a meeting. "Five villages, and mud tracks between them. I want every village reachable from every other, but the road contractor charges per road. Which roads should we build so the total bill is smallest?"

Everyone shouted a different plan. Mira's brother Kabir quietly wrote all the possible roads on slips of paper with their prices and sorted the slips from cheapest to costliest. "Take the cheapest slip. Build it. Then the next cheapest. Build it too, unless the two villages already have a way to reach each other. That road would be wasted, it only makes a loop."

Mira asked the obvious question: "How do you know if they can already reach each other?" Kabir drew a circle round each group of connected villages, like a gang. Two villages in the same gang? Skip the road. Different gangs? Build it and merge the circles. After four roads all five villages were in one gang, and Kabir stopped, even though slips were left.

That greedy slip-by-slip method is Kruskal's algorithm. The finished network is called a minimum spanning tree: it spans (touches) every village, has no loops (a tree), and the total price is the minimum. The sarpanch saved enough money to repair the school roof.

How to spot this problem, and where you need it

You have a list of possible links with costs and want to pick the cheapest subset that connects everything, without creating redundant loops.

Signs you need it

  • The input is a flat list of pairs with weights, and the wording is "minimum cost to connect all".
  • You can easily sort links by cost, and the network is sparse (few links compared with all possible pairs).
  • You need to stop early at a chosen number of groups, as in clustering.

Where to use it in a project

  • Planning features that read candidate links from a database table or CSV and return the cheapest backbone.
  • Simple clustering of products, users or locations by closeness, cut off at a set number of clusters.

The solution

Sort all links from cheapest to most expensive. Start with every node alone in its own group. Go through the links in order: if the two ends are in different groups, keep the link and merge the groups; if they are already in the same group, skip it because it would make a loop. Use Disjoint Set Union to check and merge groups fast. Stop when you have kept one fewer link than the number of nodes.

Payoff: Before: 300 candidate roads and no idea which to build. After: a sorted pass keeps the 49 cheapest that connect all 50 villages.

Explain it like I am 8

You are buying skipping-rope pieces to tie all your friends together in one chain, and each rope has a price. Buy the cheapest rope first, then the next cheapest, but never buy a rope between two friends who are already tied together, one way or another. Stop when everybody is in one big bunch.

How it works, step by step

  1. List all edges (roads) with their weights (prices) and sort them from smallest to largest.
  2. Start with every node as its own gang. (A Disjoint Set Union keeps track of the gangs, see the next lesson.)
  3. Take the cheapest unused edge. Ask: are its two ends already in the same gang?
  4. If different gangs: keep the edge and merge the gangs. If same gang: throw the edge away, it would form a loop.
  5. Stop when you have kept (number of nodes − 1) edges. That is exactly enough to connect everyone. Add up the weights for the total cost.

The code in four languages

PHP

<?php
// Find the "gang leader" of a village, shortening the chain as we climb
function findRoot(array &$parent, int $x): int {
    while ($parent[$x] !== $x) {
        $parent[$x] = $parent[$parent[$x]];   // shortcut to the grandparent
        $x = $parent[$x];
    }
    return $x;
}

function kruskal(int $n, array $roads): array {
    usort($roads, fn($a, $b) => $a[2] <=> $b[2]);   // cheapest road first
    $parent = range(0, $n - 1);                      // everyone starts alone
    $chosen = [];
    $total = 0;
    foreach ($roads as [$a, $b, $price]) {
        $ra = findRoot($parent, $a);
        $rb = findRoot($parent, $b);
        if ($ra === $rb) continue;                   // same gang: it would make a loop
        $parent[$ra] = $rb;                          // merge the two gangs
        $chosen[] = $a . '-' . $b . ' (' . $price . ')';
        $total += $price;
        if (count($chosen) === $n - 1) break;        // everyone is connected
    }
    return [$chosen, $total];
}

// villages 0..4 = A..E, roads as [from, to, price]
$roads = [[0,1,1],[2,3,2],[1,2,3],[0,2,4],[3,4,5],[1,4,6]];
[$chosen, $total] = kruskal(5, $roads);
echo 'Roads: ' . implode(', ', $chosen) . PHP_EOL;
echo 'Total price: ' . $total . PHP_EOL;

JavaScript

// Find the "gang leader" of a village, shortening the chain as we climb
function findRoot(parent, x) {
  while (parent[x] !== x) {
    parent[x] = parent[parent[x]];   // shortcut to the grandparent
    x = parent[x];
  }
  return x;
}

function kruskal(n, roads) {
  roads = roads.slice().sort((a, b) => a[2] - b[2]);   // cheapest road first
  const parent = [...Array(n).keys()];                  // everyone starts alone
  const chosen = [];
  let total = 0;
  for (const [a, b, price] of roads) {
    const ra = findRoot(parent, a);
    const rb = findRoot(parent, b);
    if (ra === rb) continue;                            // same gang: it would make a loop
    parent[ra] = rb;                                    // merge the two gangs
    chosen.push(a + '-' + b + ' (' + price + ')');
    total += price;
    if (chosen.length === n - 1) break;                 // everyone is connected
  }
  return [chosen, total];
}

// villages 0..4 = A..E, roads as [from, to, price]
const roads = [[0,1,1],[2,3,2],[1,2,3],[0,2,4],[3,4,5],[1,4,6]];
const [chosen, total] = kruskal(5, roads);
console.log('Roads: ' + chosen.join(', '));
console.log('Total price: ' + total);

Java

import java.util.*;

public class Main {
    // Find the "gang leader" of a village, shortening the chain as we climb
    static int findRoot(int[] parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];   // shortcut to the grandparent
            x = parent[x];
        }
        return x;
    }

    // roads are {from, to, price}. Fills "chosen" with the picked roads and returns the total price.
    static int kruskal(int n, int[][] roads, List<String> chosen) {
        int[][] sorted = roads.clone();
        Arrays.sort(sorted, Comparator.comparingInt(r -> r[2]));   // cheapest road first
        int[] parent = new int[n];                                 // everyone starts alone
        for (int i = 0; i < n; i++) parent[i] = i;
        int total = 0;
        for (int[] road : sorted) {
            int a = road[0], b = road[1], price = road[2];
            int ra = findRoot(parent, a);
            int rb = findRoot(parent, b);
            if (ra == rb) continue;                                // same gang: it would make a loop
            parent[ra] = rb;                                       // merge the two gangs
            chosen.add(a + "-" + b + " (" + price + ")");
            total += price;
            if (chosen.size() == n - 1) break;                     // everyone is connected
        }
        return total;
    }

    public static void main(String[] args) {
        // villages 0..4 = A..E, roads as {from, to, price}
        int[][] roads = {{0, 1, 1}, {2, 3, 2}, {1, 2, 3}, {0, 2, 4}, {3, 4, 5}, {1, 4, 6}};
        List<String> chosen = new ArrayList<>();
        int total = kruskal(5, roads, chosen);
        System.out.println("Roads: " + String.join(", ", chosen));
        System.out.println("Total price: " + total);
    }
}

Go

package main

import (
	"fmt"
	"sort"
	"strings"
)

type road struct{ a, b, price int }

// findRoot finds the "gang leader" of a village, shortening the chain as we climb.
func findRoot(parent []int, x int) int {
	for parent[x] != x {
		parent[x] = parent[parent[x]] // shortcut to the grandparent
		x = parent[x]
	}
	return x
}

func kruskal(n int, roads []road) ([]string, int) {
	sorted := append([]road(nil), roads...) // copy, keep the input safe
	// cheapest road first
	sort.Slice(sorted, func(i, j int) bool { return sorted[i].price < sorted[j].price })
	// everyone starts alone
	parent := make([]int, n)
	for i := range parent {
		parent[i] = i
	}
	var chosen []string
	total := 0
	for _, r := range sorted {
		ra := findRoot(parent, r.a)
		rb := findRoot(parent, r.b)
		if ra == rb {
			continue // same gang: it would make a loop
		}
		parent[ra] = rb // merge the two gangs
		chosen = append(chosen, fmt.Sprintf("%d-%d (%d)", r.a, r.b, r.price))
		total += r.price
		if len(chosen) == n-1 {
			break // everyone is connected
		}
	}
	return chosen, total
}

func main() {
	// villages 0..4 = A..E, roads as {from, to, price}
	roads := []road{{0, 1, 1}, {2, 3, 2}, {1, 2, 3}, {0, 2, 4}, {3, 4, 5}, {1, 4, 6}}
	chosen, total := kruskal(5, roads)
	fmt.Println("Roads: " + strings.Join(chosen, ", "))
	fmt.Println("Total price:", total)
}

Time: O(E log E) · Extra space: O(V). Sorting the roads is the expensive part; checking gangs with a Disjoint Set is almost instant.

Watch out for

  • Forgetting the loop check and simply taking the cheapest roads. You overpay for roads that connect villages that are already connected.
  • Using it on a graph that is not connected. You never reach n − 1 roads; you get a forest (one tree per piece) instead.
  • Using plain "visited" flags instead of gangs. Two villages can both be visited yet still be in different gangs.

Quick check

  1. Kruskal looks at the next cheapest road. When does it throw the road away?
    • When one end is a dead end
    • When both ends are already in the same gang
    • When the road is longer than the previous one
  2. A network has 8 villages. How many roads does the minimum spanning tree have?
    • 9
    • 6
    • 8
    • 7
  3. What is the main cost of Kruskal's algorithm?
    • Printing the answer
    • Checking the gangs
    • Sorting the edges