Introduction
Kruskal Algorithm is one of the most important algorithms for finding a Minimum Spanning Tree (MST).
You are given:
- A weighted undirected graph
- n vertices
- Weighted edges
Goal:
Find a spanning tree with minimum total weight.
Example
Input
n = 4
Edges:
0 -- 1 (10)
0 -- 2 (6)
0 -- 3 (5)
1 -- 3 (15)2 -- 3 (4)
Output
MST Cost = 19 Key Observation
Always pick the smallest weight edge that does not form a cycle.
Union Find helps efficiently detect cycles.
Algorithm
- Sort all edges by weight.
- Initialize Union Find.
- Pick the smallest edge.
- If it does not create a cycle, include it.
- Otherwise skip it.
- Continue until MST contains n-1 edges.
Dry Run
Sorted Edges
(2,3,4)(0,3,5)
(0,2,6)
(0,1,10)
(1,3,15)
Pick (2,3,4)
Cost = 4
Pick (0,3,5)
Cost = 9
Pick (0,2,6)
Creates Cycle
Skip
Pick (0,1,10)
Cost = 19
MST completed.
Answer:
19 Approach : Greedy + Union Find
Kruskal greedily picks the smallest edge available.
Union Find ensures that selected edges do not form cycles.
The resulting spanning tree has minimum possible weight.