DSA Kruskal’s Algorithm

DSA Tutorial

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

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

 One-line idea:
Pick the smallest edges one by one, and never form a cycle.


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

Given

  • A weighted, undirected graph

Find

  • A Minimum Spanning Tree

  • Minimum total edge weight

  • No cycles

  • Exactly V − 1 edges


2️⃣ When to Use Kruskal’s Algorithm

ScenarioUse Kruskal?
Sparse graph✅ Best choice
Dense graph⚠️ Prim preferred
Graph with negative weights✅ Allowed
Directed graph❌ Not applicable

3️⃣ Core Greedy Idea

  • Sort all edges by increasing weight

  • Pick the smallest edge

  • If it creates a cycle → skip

  • Continue until V − 1 edges are chosen

Cycle detection is done using Disjoint Set (Union–Find).


4️⃣ Key Concept: Disjoint Set (Union–Find)

Union–Find helps to:

  • Check if two vertices belong to the same component

  • Prevent cycles

Operations

  • find() → finds parent/root

  • union() → merges two sets


5️⃣ Step-by-Step Example

Graph (Edges with weights)

Sorted Edges

(23, 4)
(03, 5)
(02, 6)
(01, 10)
(13, 15)

Picking Edges

StepEdgeActionReason
12–3 (4)✅ AddNo cycle
20–3 (5)✅ AddNo cycle
30–2 (6)❌ SkipCycle
40–1 (10)✅ AddNo cycle

✔ MST completed with V−1 edges


6️⃣ Algorithm Steps

  1. Sort all edges by weight

  2. Initialize Disjoint Set for vertices

  3. Traverse edges in sorted order

  4. For each edge:

    • If it connects different components → add to MST

    • Else → skip

  5. Stop when MST has V−1 edges


7️⃣ Kruskal’s Algorithm – C++ Implementation


 


8️⃣ Time & Space Complexity

Time Complexity

O(E log E)

(Sorting edges dominates)

 Space Complexity

O(V)

9️⃣ Kruskal vs Prim

FeatureKruskalPrim
Best forSparse graphsDense graphs
Data structureUnion–FindPriority Queue
SortingEdgesVertices
Start vertexNot requiredRequired

🔟 Common Mistakes

❌ Forgetting to sort edges
❌ Not using Union–Find
❌ Applying on directed graph
❌ Confusing MST with shortest path


 Interview Questions (Very Important)

Q1. Why does Kruskal pick edges in sorted order?
👉 Greedy choice ensures minimum total weight

Q2. Why Union–Find is needed?
👉 To detect cycles efficiently

Q3. Can Kruskal work with negative weights?
👉 ✅ Yes

Q4. When is MST unique?
👉 When all edge weights are distinct


 Final Summary

✔ Greedy MST algorithm
✔ Sort edges → pick smallest
✔ Uses Union–Find to avoid cycles
✔ Best for sparse graphs
✔ Time complexity: O(E log E)

You may also like...