Browse Curriculum

Minimum Spanning Tree (MST)

Learn how to connect all vertices in a graph with the minimum total edge weight using Prim's and Kruskal's algorithms.

4231582ABCDE
Algorithm: Prim's

Ready to start

Speed
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Intuition

Prim's Algorithm: Imagine a mold spreading from a single point. It keeps adding the nearest node to the growing blob until everything is covered.

Kruskal's Algorithm: Imagine building bridges. You always build the cheapest bridge available anywhere on the map, unless it connects two islands that are already connected (which would be redundant).

Concept

A Spanning Tree is a subgraph that connects all vertices without any cycles. A Minimum Spanning Tree (MST) is the spanning tree with the lowest total edge weight.

  • Prim's (Node-based): Grows a single tree from a starting node. Best for dense graphs.
  • Kruskal's (Edge-based): Adds edges from lightest to heaviest, merging disjoint sets. Best for sparse graphs.

How it Works

Prim's Steps:
  1. Start with an arbitrary node.
  2. Add all connected edges to a Priority Queue.
  3. Pick the smallest edge connecting a visited node to an unvisited one.
  4. Add the new node to the MST set.
  5. Repeat until all nodes are visited.
Kruskal's Steps:
  1. Sort all edges by weight (ascending).
  2. Iterate through sorted edges.
  3. For each edge (u, v), check if u and v are already connected (using Union-Find).
  4. If not connected, add edge to MST and union the sets.
  5. If connected, skip to avoid cycles.

Step-by-Step Breakdown

Watch the visualization:

  • Emerald Edge: Part of the finalized MST.
  • Orange Edge: Currently being considered / processed.
  • Red Edge (Kruskal's): Rejected because it forms a cycle.

When to Use

Applications:

  • Network design (telecom cables, water pipes, road networks).
  • Clustering algorithms in Machine Learning.
  • Approximation algorithms for NP-hard problems (like TSP).

When NOT to Use

  • Shortest Paths: MST minimizes total weight, not the path distance between two specific nodes (use Dijkstra).
  • Directed Graphs: Standard Prim's/Kruskal's apply to undirected graphs. For directed MST, use the Chu-Liu/Edmonds algorithm.

How to Identify

"Connect all points with minimum cost", "Design a network with least cable".

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep