Quick reference
Kruskal's algorithm finds a minimum spanning tree by sorting a graph's edges from cheapest to most expensive and adding each edge that doesn't create a cycle, until every node is connected. It uses a union-find data structure to tell, almost instantly, whether an edge would create a cycle.
The steps:
- Sort the edges by weight, cheapest first.
- Start with every node in a group of its own.
- Go through the edges in order. If an edge's two ends are in different groups, add the edge to the tree and merge the two groups. If they're already in the same group, skip the edge: it would close a cycle.
- Stop once the tree has V - 1 edges, where V is the number of nodes.
Cost:
- O(E log E) time, which is the same as O(E log V), where E is the number of edges. Sorting the edges is the slow part. The union-find checks are nearly constant time each.
- O(V + E) space for the union-find and the sorted list of edges.
Works on:
- Connected, undirected, weighted graphs. Negative weights are fine. On a graph that isn't connected, it finds a minimum spanning forest: the cheapest tree for each connected piece.
How Kruskal's Algorithm Works
A minimum spanning tree (MST) is the cheapest set of edges that connects every node in a graph without any cycles. Kruskal's algorithm, published by Joseph Kruskal in 1956, builds one by always grabbing the cheapest edge it can use. That makes it a greedy algorithm: it makes the choice that looks best right now and never goes back on it.
Picture every node as a tiny tree of its own, so we start with a forest of V one-node trees. Each edge we add joins two of those trees into one bigger tree. Every join leaves one fewer tree, so after V - 1 joins there's a single tree, and it reaches every node.
There's one rule: never add an edge whose two ends are already in the same tree. Those two nodes are already connected by some path, so the new edge would close a loop (a cycle), and a tree can't have cycles. It would also waste money: we'd be paying for a connection we already have.
Here's the whole algorithm in pseudocode. The find and
union operations come from a union-find, which we'll get
to below:
Why go cheapest first? Because the cheapest edge that joins two separate trees is always safe to take: there's a minimum spanning tree that uses it. That's what makes this greedy approach give the best possible answer. We'll see why it works after the example.
Kruskal's Algorithm Example, Step by Step
Say your bakery has six shops, A through F, and you want to connect them all to one network so every shop can see every other shop's orders. Picture the shops in two rows: A, B, and C on top, with D, E, and F underneath them. You can run a cable between some pairs of shops, and each cable run has a different cost, in thousands of dollars:
| Cable run (edge) | Cost (weight) |
|---|---|
| A-B | 4 |
| A-D | 2 |
| A-E | 5 |
| B-C | 7 |
| B-E | 3 |
| C-E | 8 |
| C-F | 1 |
| D-E | 6 |
| E-F | 9 |
We want the cheapest set of cables that connects all six shops: a minimum spanning tree of this graph. It has 6 nodes, so the tree will have 5 edges.
First, sort the edges by cost: C-F (1), A-D (2), B-E (3), A-B (4), A-E (5), D-E (6), B-C (7), C-E (8), E-F (9). Every shop starts out in a group of its own: {A} {B} {C} {D} {E} {F}. Then go down the sorted list:
| Step | Edge (cost) | Ends already in the same group? | Decision | Groups afterward | Total so far |
|---|---|---|---|---|---|
| 1 | C-F (1) | No | Add it | {A} {B} {C, F} {D} {E} | 1 |
| 2 | A-D (2) | No | Add it | {A, D} {B} {C, F} {E} | 3 |
| 3 | B-E (3) | No | Add it | {A, D} {B, E} {C, F} | 6 |
| 4 | A-B (4) | No: A is in {A, D}, B is in {B, E} | Add it | {A, B, D, E} {C, F} | 10 |
| 5 | A-E (5) | Yes: both in {A, B, D, E} | Skip it (it would close the cycle A-B-E) | {A, B, D, E} {C, F} | 10 |
| 6 | D-E (6) | Yes: both in {A, B, D, E} | Skip it (it would close the cycle D-A-B-E) | {A, B, D, E} {C, F} | 10 |
| 7 | B-C (7) | No: B is in {A, B, D, E}, C is in {C, F} | Add it. That's 5 edges, so stop. | {A, B, C, D, E, F} | 17 |
We never even look at C-E (8) or E-F (9). The minimum spanning tree is C-F, A-D, B-E, A-B, and B-C, for a total cost of 17 ($17,000). Since every cable run has a different cost, it's the only spanning tree that cheap.
Two steps are worth a second look:
- Step 4. By this point, A and B have both been touched (A by A-D, B by B-E), but they're in different groups, so A-B is fine to add. That's why we track groups, not just which nodes we've seen. See common mistakes below.
- Step 5. A-E (5) is cheaper than B-C (7), but it doesn't make the cut. By the time we reach it, A and E are already connected (through B), so it would only add a cycle.
Detecting Cycles with Union-Find
The only tricky part of Kruskal's algorithm is step 3: how do we know whether an edge's two ends are already connected?
The slow way is to search the tree we've built so far, with a depth-first or breadth-first search, starting at one end of the edge and checking whether we can reach the other. That's O(V) time per edge, or O(EV) overall, which is too slow for big graphs.
The fast way is a union-find (also called a disjoint set union, or DSU). It keeps track of which group each node is in, with two operations:
- find(node) returns the root of the node's group: one node that represents the whole group. Two nodes are in the same group exactly when they have the same root.
- union(node1, node2) merges the groups holding the two nodes into one.
For each edge, Kruskal's algorithm finds the roots of both ends. If the roots match, the edge would close a cycle, so we skip it. If they don't, we add the edge and union the two groups.
With two standard tricks, path compression (as
find walks up toward the root, it points nodes closer to
the root, so later lookups are shorter) and union by
size (hang the smaller group under the bigger one), each
operation takes O(α(V)) amortized
time. α is the inverse Ackermann function, which grows so slowly that
it's less than 5 for any graph you'll ever see. In practice, that's
constant time. (Our code uses path halving, a
one-loop form of path compression that points each node it passes at
its grandparent. It has the same guarantee.)
The code below includes a compact union-find. For how it works, step by step, and why those two tricks make it so fast, see our union-find page.
Kruskal's Algorithm Code
Here's Kruskal's algorithm with a compact union-find built in. Nodes are numbered 0 to V - 1 (shop A is 0, B is 1, and so on), and each edge is a (node1, node2, weight) triple:
Running it on the bakery graph prints the edges in the order Kruskal's algorithm adds them, matching the table above:
C-F 1 A-D 2 B-E 3 A-B 4 B-C 7 Total: 17
A few details:
- We sort a copy of the edges, so the caller's list isn't reordered.
- We stop as soon as we have V - 1 edges. That's optional (no later edge could be added anyway), but it skips the rest of the list, like C-E and E-F above.
- If the graph isn't connected, there's no spanning tree, and we run out of edges before reaching V - 1. The function then returns a minimum spanning forest: the cheapest tree for each connected piece. If you need a single tree, check that you got V - 1 edges. (Many interview versions of this problem ask you to return −1 when that check fails.)
- Ties can go in any order. If two edges cost the same, sorting might put either one first. You might end up with a different tree, but its total cost will be the same.
Kruskal's Algorithm Time Complexity
| Step | Time |
|---|---|
| Sort the E edges | O(E log E) |
| Set up the union-find | O(V) |
| Up to E find-and-union checks | O(E α(V)), which is nearly O(E) |
| Total | O(E log E), the same as O(E log V) |
Sorting is the bottleneck, so Kruskal's algorithm takes O(E log E) time.
You'll often see it written as O(E log V) instead. They mean the same thing. A graph without duplicate edges has at most V(V - 1)/2 edges, so E < V^2, which means \log E < \log V^2 = 2 \log V. Big O ignores constant factors like that 2, so O(E log E) = O(E log V). (For more on reading these, see our big O notation guide.)
If the edges come already sorted, or their weights are small whole numbers you can sort in linear time with counting sort, sorting stops being the bottleneck, and the whole algorithm runs in nearly linear time, O(E α(V)).
Space: O(V) for the union-find's arrays and the tree, plus O(E) for the sorted copy of the edges, for O(V + E) in total.
Why Kruskal's Algorithm Works
Greedy algorithms don't always find the best answer. So why does this one?
It comes down to the cut property of minimum spanning trees: split the nodes into any two sides, and the cheapest edge that crosses between the sides belongs to a minimum spanning tree. (Our minimum spanning tree page shows why that's true.)
Now take any edge Kruskal's algorithm adds. Call its ends u and v. Just before we add it, u and v are in different groups. Split the nodes into two sides: u's group on one side, every other node on the other. The edge crosses between them.
Could a cheaper edge cross between those sides? It would have come earlier in the sorted order. Back then, its two ends were in different groups too (groups only ever merge, and its ends are on different sides now), so Kruskal's algorithm would have added it and merged their groups. Then its ends would be on the same side now. That's a contradiction, so no cheaper edge crosses. The edge we're adding is a cheapest crossing edge, and the cut property says adding it keeps us on track: there's still a minimum spanning tree that contains every edge we've picked so far.
Skipping edges is safe too. A skipped edge connects two nodes that are already connected by edges that cost no more than it does, so it can only close a cycle. (That's the cycle property: the most expensive edge on a cycle is never needed.)
Kruskal's vs. Prim's Algorithm
Prim's algorithm is the other classic way to find a minimum spanning tree. Instead of going through every edge in the graph in sorted order, it grows a single tree outward from a starting node, always adding the cheapest edge that leaves the tree.
On the bakery graph, both find the same tree, with a total of 17, but they add the edges in a different order:
| Order the edges are added | |
|---|---|
| Kruskal's | C-F (1), A-D (2), B-E (3), A-B (4), B-C (7) |
| Prim's, starting at A | A-D (2), A-B (4), B-E (3), B-C (7), C-F (1) |
Kruskal's takes the cheapest edge in the whole graph, C-F, first. Prim's doesn't add C-F until the very end, because it can only use edges that touch the tree it has built so far, and its tree doesn't reach C until the fourth edge.
| Kruskal's algorithm | Prim's algorithm | |
|---|---|---|
| How the tree grows | As a forest of small trees that merge into one | As one tree that spreads out from a start node |
| Next edge | The cheapest remaining edge anywhere that doesn't close a cycle | The cheapest edge from the tree to a node outside it |
| Data structures | Sorted edge list and a union-find | Priority queue (min-heap) and an adjacency list |
| Time | O(E log E), the same as O(E log V) | O(E log V) with a binary heap, or O(V²) with a plain array |
| Best for | Sparse graphs, especially when you're given a list of edges | Dense graphs (the O(V²) version), and graphs stored as adjacency lists |
| Graph isn't connected | Finds a minimum spanning forest | Only spans the start node's connected piece |
A good rule of thumb for interviews: if the input is a list of edges, Kruskal's algorithm is usually the shortest code to write. If every pair of nodes is connected (like "connect all these points"), Prim's O(V²) version is faster.
Common Mistakes
-
Checking "have I seen both ends?" instead of "are both ends in the same group?" A set of visited nodes isn't enough. On the bakery graph, after C-F, A-D, and B-E, all of A, B, C, D, E, and F have been seen, so that check skips every remaining edge. You'd end up with 3 disconnected pieces instead of a tree. A and B were both seen, but they weren't connected yet. Only a union-find (or a search) can tell the difference.
-
Sorting wrong. Sort by weight, not by node. In JavaScript,
sort()without a comparator compares items as strings, so[10, 9, 1].sort()gives[1, 10, 9]. Always pass one. In Java, a comparator that returnsa[2] - b[2]can overflow when weights are huge or very negative.Integer.compareis safe. -
A union-find without path compression or union by size. Without them, groups can turn into long chains, and each
findcan take O(V) time. That makes the whole algorithm O(EV) in the worst case. -
Assuming the graph is connected. If it isn't, there's no spanning tree, and you'll end up with fewer than V - 1 edges. Check the count before you report an answer.
-
Using it on a directed graph. Minimum spanning trees are for undirected graphs. The directed version (a minimum spanning arborescence, where every node is reachable from a root) needs a different algorithm, like Chu-Liu/Edmonds'.
-
Expecting shortest paths. In the bakery MST, the route from A to E goes A-B-E and costs 7, even though the direct cable A-E costs 5. An MST keeps the total cost low, not the cost between any two particular nodes. For the cheapest route between nodes, use Dijkstra's algorithm.
Interview Problems That Use Kruskal's Algorithm
- Connect every city (or computer, or shop) at the lowest total cost. That's Kruskal's algorithm as written above. Return −1 (or whatever the problem asks for) if you end up with fewer than V - 1 edges.
- Connect all these points. When any two points can be connected (at a cost like their distance), the graph is complete, with V(V - 1)/2 edges. Kruskal's algorithm works, in O(V² log V) time, but Prim's algorithm can do it in O(V²).
- Find a maximum spanning tree. Sort from most expensive to cheapest instead. (The bakery graph's most expensive spanning tree costs 35.)
- Build a well, or pipe water in from a neighbor. When each node can either pay to supply itself or connect to another node, add a made-up node 0 with an edge to every real node that costs as much as supplying that node itself. Then run Kruskal's algorithm on the bigger graph.
- Group items into k clusters. Run Kruskal's algorithm, but stop when only k groups are left. This is single-linkage clustering, and it makes the closest pair of items in different clusters as far apart as possible.
- Find the edges every MST needs. An edge is critical if leaving it out makes the minimum spanning tree more expensive (or impossible). Run Kruskal's without the edge and compare totals.
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake