Day 45: Kruskal's Algorithm
Kruskal’s Algorithm#
Welcome to Day 45 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore Kruskal’s Algorithm, another greedy algorithm used for finding the Minimum Spanning Tree (MST) of a weighted undirected graph.
What is Kruskal’s Algorithm?#
Kruskal’s Algorithm is a minimum-spanning-tree algorithm which finds an edge of the least possible weight that connects any two trees in the forest. It is a greedy algorithm in graph theory as it finds a minimum spanning tree for a connected weighted graph adding increasing cost arcs at each step.
How Kruskal’s Algorithm Works#
- Sort all the edges from low weight to high.
- Take the edge with the lowest weight and add it to the spanning tree. If adding the edge created a cycle, then reject this edge.
- Keep adding edges until we reach all vertices.
Implementation#
Let’s implement Kruskal’s Algorithm in Python:
1class DisjointSet:
2 def __init__(self, vertices):
3 self.parent = {v: v for v in vertices}
4 self.rank = {v: 0 for v in vertices}
5
6 def find(self, item):
7 if self.parent[item] != item:
8 self.parent[item] = self.find( …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating