DSA Notes
Learn Kruskal\
The Approach
Kruskal's algorithm finds the MST with a beautifully simple greedy strategy:
- Sort all edges by weight (smallest first)
- For each edge, if it connects two different components, add it to MST
- Stop when MST has V-1 edges
The key challenge is step 2: how do we efficiently check if two vertices are already in the same component? The answer is Union-Find (Disjoint Set Union), which makes this check nearly O(1).
Algorithm Steps
Step-by-Step Example
| Step 1: Edge (2,3,1) — vertices 2,3 in different sets | ADD |
| Components | {0}{1}{2,3}{4}{5} MST weight: 1 |
| Step 2: Edge (0,1,2) — vertices 0,1 in different sets | ADD |
| Components | {0,1}{2,3}{4}{5} MST weight: 3 |
| Step 3: Edge (1,3,3) — vertex 1 in {0,1}, vertex 3 in {2,3} | ADD |
| Components | {0,1,2,3}{4}{5} MST weight: 6 |
| Step 4: Edge (0,2,4) — vertices 0,2 both in {0,1,2,3} | SKIP (cycle!) |
| Step 5: Edge (3,4,5) — vertex 3 in {0,1,2,3}, vertex 4 in {4} | ADD |
| Components | {0,1,2,3,4}{5} MST weight: 11 |
| Step 6: Edge (4,5,6) — vertex 4 in {0,1,2,3,4}, vertex 5 in {5} | ADD |
| Components | {0,1,2,3,4,5} MST weight: 17 |
| MST edges | (2,3,1), (0,1,2), (1,3,3), (3,4,5), (4,5,6) |
| Total weight | 17 |
Python Implementation
C++ Implementation
Time and Space Complexity
- Time: O(E log E) for sorting + O(E × α(V)) for Union-Find operations ≈ O(E log E)
- Since E ≤ V², log E ≤ 2 log V, so this is also O(E log V)
- α(V) is the inverse Ackermann function, practically constant (~4)
- Space: O(V + E) — Union-Find uses O(V), edge list uses O(E)
Kruskal's vs Prim's
| Aspect | Kruskal's | Prim's |
|---|---|---|
| Strategy | Sort edges, add safely | Grow tree from vertex |
| Data structure | Union-Find | Priority Queue |
| Time | O(E log E) | O(E log V) |
| Best for | Sparse graphs (E ≈ V) | Dense graphs (E ≈ V²) |
| Edge list input | Natural fit | Needs adjacency list |
| Parallelizable | Yes (independent edge checks) | Less so |
Why Kruskal's is Correct
Kruskal's works because of the cut property: at each step, the lightest edge connecting two different components crosses some cut of the graph. By the cut property, this edge must be in the MST. Since we process edges in weight order, we always pick the correct minimum crossing edge for each cut we encounter.
Applications
- Network design: Minimum cost to connect all nodes (cable, pipe, road)
- Clustering: Remove the k-1 heaviest MST edges to get k clusters
- Approximation: 2-approximation for metric TSP
- Image segmentation: Pixels as vertices, similarity as edge weights
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Kruskal\.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, graphs, kruskals, algorithm
Related Data Structures & Algorithms Topics