Algorithms · Visualized
Kruskal's MST
Graph Algorithms
Traverse, order, and find shortest paths and spanning trees on graphs — the machinery behind maps, networks, schedulers and dependency resolvers.
Kruskal builds the MST by scanning all edges from lightest to heaviest and accepting any edge whose endpoints are still in different components — an edge inside the same component would close a cycle, so it is rejected. Time: O(E log E) average, O(E log E) worst; space: O(V) for the union-find parent array.
Big-O: Traversals O(V + E); Dijkstra O(E log V) with a heap; Bellman–Ford O(V·E); Floyd–Warshall O(V³); MST O(E log E).
Kruskal's Minimum Spanning Tree
Graph AlgorithmsKruskal builds the MST by scanning all edges from lightest to heaviest and accepting any edge whose endpoints are still in different components — an edge inside the same component would close a cycle, so it is rejected. A union-find (disjoint set) answers 'same component?' in near-constant time, making the whole algorithm O(E log E).
How Kruskal's MST Works
- Sort every edge by weight, ascending.
- Put each node in its own component (union-find with itself as parent).
- Walk the sorted edges: find the roots of both endpoints.
- If the roots differ, accept the edge, add its weight, and union the components.
- If the roots match, reject — the edge would create a cycle. Stop after V−1 acceptances.
Kruskal's MST Worked Example
Input: {graph: A—B(4), A—C(2), B—C(1), B—D(5), C—D(8), C—E(10), D—E(2), D—F(6), E—F(3), start: —}
Sorted: B—C(1), A—C(2), D—E(2), E—F(3), A—B(4), B—D(5), D—F(6), C—D(8), C—E(10). Accept B—C, A—C, D—E, E—F; reject A—B (cycle A-C-B); accept B—D → 5 edges. Total 13, same tree as Prim found.
def kruskal_mst(n, edges):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path compression
x = parent[x]
return x
total = 0
for u, v, w in sorted(edges, key=lambda e: e[2]):
ru, rv = find(u), find(v)
if ru != rv: # different components: accept
parent[ru] = rv
total += w
return totalBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Kruskal's MST Time & Space Complexity
When to Use Kruskal's MST
- Sparse or edge-list graphs — Kruskal needs no adjacency structure, just a sorted edge list.
- Clustering: stopping Kruskal early (single-link clustering) groups data instead of connecting it.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.