A Minimum Spanning Tree (MST) is a subset of edges in a connected, weighted, undirected graph that connects all the vertices together without any cycles and with the minimum possible total edge weight.
Vertices: A, B, C, D, E Edges: A-B (2), A-C (3), B-C (1), B-D (4), C-D (5), D-E (7)
The MST will connect all vertices (A–E) with the minimum total cost.
Kruskal’s algorithm builds the MST by adding edges in increasing order of their weights while avoiding cycles. It uses a Disjoint Set Union (DSU) or Union-Find data structure.
Edges sorted by weight → pick (B–C), (A–B), (B–D), (D–E) Total MST weight = 2 + 1 + 4 + 7 = 14
Prim’s algorithm starts from one vertex and grows the MST by adding the smallest edge that connects a visited vertex to an unvisited vertex.
Start at A → Add edges (A–B), (B–C), (B–D), (D–E) Total MST weight = 14
| Feature | Prim’s Algorithm | Kruskal’s Algorithm |
|---|---|---|
| Approach | Grows MST from one vertex | Adds edges in sorted order |
| Data Structure | Priority Queue (Min-Heap) | Disjoint Set (Union-Find) |
| Works Best For | Dense Graphs | Sparse Graphs |
| Time Complexity | O(E log V) | O(E log E) |
| Cycle Checking | Implicit via visited set | Explicit via DSU |
Prim’s and Kruskal’s algorithms both find the Minimum Spanning Tree of a weighted graph but differ in approach. Choosing between them depends on the graph’s density and representation. Understanding both is crucial in algorithm design, optimization, and competitive programming.
Take quizzes related to this topic and see where you stand!
Start Quiz Now