DSA Minimum Spanning Tree

DSA Tutorial

DSA Minimum Spanning Tree (MST) 
(Concept • Properties • Algorithms • Examples • Code • Complexity • Interview Tips)

A Minimum Spanning Tree (MST) is one of the most important graph topics in DSA and interviews.


 What is a Spanning Tree?

For a connected, undirected graph:

  • Uses all vertices

  • Contains no cycles

  • Has exactly V − 1 edges


 What is a Minimum Spanning Tree (MST)?

Among all possible spanning trees, the MST is the one with the minimum total edge weight.

 In short:

Connect all vertices with minimum cost and no cycles


 Where is MST Used?

✔ Network cable laying
✔ Road / railway planning
✔ Electrical grids
✔ Cluster analysis
✔ Minimum cost infrastructure design


 Key Properties of MST

  • Exists only for connected graphs

  • Works on undirected graphs

  • No cycles allowed

  • If graph has V vertices → MST has V−1 edges

  • MST may not be unique (if weights repeat)


 Example Graph


 

✔ MST picks lowest-weight edges without forming cycles.


 Two Famous MST Algorithms

Algorithm Best Use Case
Kruskal’s Algorithm Sparse graphs
Prim’s Algorithm Dense graphs

1️⃣ Kruskal’s Algorithm

 Idea

  • Sort all edges by weight

  • Pick the smallest edge

  • Avoid cycles using Disjoint Set (Union-Find)

 Steps

  1. Sort edges by weight

  2. Pick smallest edge

  3. If it forms a cycle → skip

  4. Repeat until V−1 edges

 Complexity

O(E log E)

 Kruskal – C++ Code


 


2️⃣ Prim’s Algorithm

 Idea

  • Start from any vertex

  • Always pick minimum weight edge connected to MST

  • Similar to Dijkstra, but for MST

 Steps

  1. Start from a node

  2. Pick smallest edge connecting MST → new node

  3. Repeat until all nodes included

 Complexity

O(E log V) (using priority queue)

 Prim – C++ Code


 


 Kruskal vs Prim

Feature Kruskal Prim
Graph type Sparse Dense
Data structure Union-Find Priority Queue
Sorting Edges Vertices
Starting node Not needed Required

 MST vs Shortest Path

Feature MST Shortest Path
Goal Min total cost Min distance from source
Cycles Allowed
Algorithms Kruskal, Prim Dijkstra, Bellman-Ford

 Interview Questions (Very Important)

Q1. Why MST has V−1 edges?
👉 To connect all vertices without cycles

Q2. Can MST exist in directed graph?
👉 ❌ No (standard MST is for undirected graphs)

Q3. Can MST be unique?
👉 Only if all edge weights are distinct


 Final Summary

✔ MST connects all vertices with minimum cost
✔ Used in real-life network problems
✔ Two algorithms: Kruskal & Prim
✔ No cycles, exactly V−1 edges
✔ Core DSA + interview favorite

You may also like...