DSA — Kruskal's Algorithm
What is Kruskal's Algorithm?
Finds the minimum spanning tree by adding edges in order of weight.
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px == py:
return False
if self.rank[px] < self.rank[py]:
px, py = py, px
self.parent[py] = px
if self.rank[px] == self.rank[py]:
self.rank[px] += 1
return True
def kruskal(edges, n):
edges.sort(key=lambda x: x[2])
uf = UnionFind(n)
mst = []
for u, v, weight in edges:
if uf.union(u, v):
mst.append((u, v, weight))
if len(mst) == n - 1:
break
return mst
Time Complexity
| Operation | Complexity |
|---|---|
| Sort edges | O(E log E) |
| Union-Find operations | O(E α(V)) |
Applications
- Network design
- Clustering
- Approximation algorithms
Mini Practice
- Implement Kruskal's algorithm
- Use Union-Find data structure
- Find minimum spanning tree
- Compare with Prim's algorithm
Up Next
Continue with Prim's Algorithm — another MST algorithm.
Related Topics
Frequently Asked Questions about Kruskal's Algorithm
What is Kruskal's Algorithm in DSA?
Kruskal's Algorithm is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Kruskal's Algorithm?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Kruskal's Algorithm.
Why is Kruskal's Algorithm important in DSA?
Kruskal's Algorithm is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.