DSA Prim’s Algorithm

DSA Tutorial

DSA – Prim’s Algorithm (Minimum Spanning Tree)
(Concept • Steps • Example • Dry Run • Code • Complexity • Interview Tips)

Prim’s Algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected, weighted, undirected graph.

 Idea in one line:
Grow the MST one vertex at a time by always choosing the minimum weight edge that connects a new vertex.


1️⃣ What Problem Does Prim’s Algorithm Solve?

Given

  • A connected, undirected, weighted graph

Find

  • A Minimum Spanning Tree

  • Total weight is minimum

  • No cycles

  • Exactly V − 1 edges


2️⃣ When to Use Prim’s Algorithm

ScenarioUse Prim’s?
Dense graph✅ Best choice
Sparse graph⚠️ Kruskal better
Negative weights✅ Allowed
Directed graph❌ Not applicable

3️⃣ Core Greedy Idea

  • Start from any vertex

  • Repeatedly pick the minimum weight edge

  • The edge must:

    • Connect MST → non-MST vertex

    • Not form a cycle

 Similar to Dijkstra, but goal is minimum total cost, not shortest path.


4️⃣ Step-by-Step Example


 

Start from A

StepPicked EdgeMST NodesTotal Weight
1A–B (2)A,B2
2B–C (3)A,B,C5
3C–D (5)A,B,C,D10

 MST complete (V−1 edges)


5️⃣ Algorithm Steps

  1. Pick any start vertex

  2. Mark it as visited

  3. Push all connected edges into min-heap

  4. Extract minimum edge

  5. If it connects to an unvisited vertex:

    • Add to MST

    • Mark vertex visited

  6. Repeat until all vertices included


6️⃣ Prim’s Algorithm – C++ (Priority Queue)


 


7️⃣ Time & Space Complexity

ImplementationTime Complexity
Adjacency MatrixO(V²)
Priority Queue (Adj List)O(E log V)

Space Complexity: O(V + E)


8️⃣ Prim vs Dijkstra (Very Important)

FeaturePrimDijkstra
GoalMinimum spanning treeShortest path
Cycles❌ Not allowedAllowed
Negative edges
OutputV−1 edgesDistance array

9️⃣ Common Mistakes

❌ Using Prim on disconnected graph
❌ Applying it to directed graph
❌ Forgetting to use min-heap
❌ Confusing it with Dijkstra


🔟 Interview Questions

Q1. Why Prim uses greedy approach?
👉 Choosing locally minimum edge leads to global minimum MST

Q2. Can Prim start from any vertex?
👉 Yes, MST weight remains same

Q3. Is MST always unique?
👉 Only when all edge weights are distinct


Final Summary

✔ Prim’s Algorithm finds Minimum Spanning Tree
✔ Greedy + Priority Queue
✔ Best for dense graphs
✔ Time complexity: O(E log V)
✔ Core topic for DSA & interviews

You may also like...