Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Difference between Prim's and Kruskal's algorithm for MST
Next article icon

Kruskal’s Minimum Spanning Tree (MST) Algorithm

Last Updated : 05 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected, and undirected graph is a spanning tree (no cycles and connects all vertices) that has minimum weight. The weight of a spanning tree is the sum of all edges in the tree.  

In Kruskal’s algorithm, we sort all edges of the given graph in increasing order. Then it keeps on adding new edges and nodes in the MST if the newly added edge does not form a cycle. It picks the minimum weighted edge at first and the maximum weighted edge at last. Thus we can say that it makes a locally optimal choice in each step in order to find the optimal solution. Hence this is a Greedy Algorithm.

How to find MST using Kruskal’s algorithm?

Below are the steps for finding MST using Kruskal’s algorithm:

  • Sort all the edges in a non-decreasing order of their weight. 
  • Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If the cycle is not formed, include this edge. Else, discard it. 
  • Repeat step 2 until there are (V-1) edges in the spanning tree.

Kruskal’s Algorithm uses the Disjoint Set Data Structure to detect cycles. 

Illustration:

The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will be having (9 – 1) = 8 edges.


C++
#include <bits/stdc++.h> using namespace std;  // Disjoint set data struture class DSU {     vector<int> parent, rank;  public:     DSU(int n) {         parent.resize(n);         rank.resize(n);         for (int i = 0; i < n; i++) {             parent[i] = i;             rank[i] = 1;         }     }      int find(int i) {         return (parent[i] == i) ? i : (parent[i] = find(parent[i]));     }      void unite(int x, int y) {         int s1 = find(x), s2 = find(y);         if (s1 != s2) {             if (rank[s1] < rank[s2]) parent[s1] = s2;             else if (rank[s1] > rank[s2]) parent[s2] = s1;             else parent[s2] = s1, rank[s1]++;         }     } }; bool comparator(vector<int> &a,vector<int> &b){     if(a[2]<=b[2])return true;     return false; } int kruskalsMST(int V, vector<vector<int>> &edges) {          // Sort all edhes     sort(edges.begin(), edges.end(),comparator);          // Traverse edges in sorted order     DSU dsu(V);     int cost = 0, count = 0;          for (auto &e : edges) {         int x = e[0], y = e[1], w = e[2];                  // Make sure that there is no cycle         if (dsu.find(x) != dsu.find(y)) {             dsu.unite(x, y);             cost += w;             if (++count == V - 1) break;         }     }     return cost; }  int main() {          // An edge contains, weight, source and destination     vector<vector<int>> edges = {         {0, 1, 10}, {1, 3, 15}, {2, 3, 4}, {2, 0, 6}, {0, 3, 5}     };          cout<<kruskalsMST(4, edges);          return 0; } 
C
// C code to implement Kruskal's algorithm  #include <stdio.h> #include <stdlib.h>  // Comparator function to use in sorting int comparator(const int p1[], const int p2[]) {     return p1[2] - p2[2]; }  // Initialization of parent[] and rank[] arrays void makeSet(int parent[], int rank[], int n) {     for (int i = 0; i < n; i++) {         parent[i] = i;         rank[i] = 0;     } }  // Function to find the parent of a node int findParent(int parent[], int component) {     if (parent[component] == component)         return component;      return parent[component]            = findParent(parent, parent[component]); }  // Function to unite two sets void unionSet(int u, int v, int parent[], int rank[], int n) {     // Finding the parents     u = findParent(parent, u);     v = findParent(parent, v);      if (rank[u] < rank[v]) {         parent[u] = v;     }     else if (rank[u] > rank[v]) {         parent[v] = u;     }     else {         parent[v] = u;          // Since the rank increases if         // the ranks of two sets are same         rank[u]++;     } }  // Function to find the MST int kruskalAlgo(int n, int edge[n][3]) {     // First we sort the edge array in ascending order     // so that we can access minimum distances/cost     qsort(edge, n, sizeof(edge[0]), comparator);      int parent[n];     int rank[n];      // Function to initialize parent[] and rank[]     makeSet(parent, rank, n);      // To store the minimun cost     int minCost = 0;     for (int i = 0; i < n; i++) {         int v1 = findParent(parent, edge[i][0]);         int v2 = findParent(parent, edge[i][1]);         int wt = edge[i][2];          // If the parents are different that         // means they are in different sets so         // union them         if (v1 != v2) {             unionSet(v1, v2, parent, rank, n);             minCost += wt;         }     }      return minCost; }  // Driver code int main() {     int edge[5][3] = { { 0, 1, 10 },                        { 0, 2, 6 },                        { 0, 3, 5 },                        { 1, 3, 15 },                        { 2, 3, 4 } };      printf("%d",kruskalAlgo(5, edge));      return 0; } 
Java
import java.util.Arrays; import java.util.Comparator;  class GfG {     public static int kruskalsMST(int V, int[][] edges) {                  // Sort all edges based on weight         Arrays.sort(edges, Comparator.comparingInt(e -> e[2]));                  // Traverse edges in sorted order         DSU dsu = new DSU(V);         int cost = 0, count = 0;                  for (int[] e : edges) {             int x = e[0], y = e[1], w = e[2];                          // Make sure that there is no cycle             if (dsu.find(x) != dsu.find(y)) {                 dsu.union(x, y);                 cost += w;                 if (++count == V - 1) break;             }         }         return cost;     }      public static void main(String[] args) {                  // An edge contains, weight, source and destination         int[][] edges = {             {0, 1, 10}, {1, 3, 15}, {2, 3, 4}, {2, 0, 6}, {0, 3, 5}         };                 System.out.println(kruskalsMST(4, edges));     } }  // Disjoint set data structure class DSU {     private int[] parent, rank;      public DSU(int n) {         parent = new int[n];         rank = new int[n];         for (int i = 0; i < n; i++) {             parent[i] = i;             rank[i] = 1;         }     }      public int find(int i) {         if (parent[i] != i) {             parent[i] = find(parent[i]);         }         return parent[i];     }      public void union(int x, int y) {         int s1 = find(x);         int s2 = find(y);         if (s1 != s2) {             if (rank[s1] < rank[s2]) {                 parent[s1] = s2;             } else if (rank[s1] > rank[s2]) {                 parent[s2] = s1;             } else {                 parent[s2] = s1;                 rank[s1]++;             }         }     } } 
Python
from functools import cmp_to_key  def comparator(a,b):     return a[2] - b[2];  def kruskals_mst(V, edges):      # Sort all edges     edges = sorted(edges,key=cmp_to_key(comparator))          # Traverse edges in sorted order     dsu = DSU(V)     cost = 0     count = 0     for x, y, w in edges:                  # Make sure that there is no cycle         if dsu.find(x) != dsu.find(y):             dsu.union(x, y)             cost += w             count += 1             if count == V - 1:                 break     return cost      # Disjoint set data structure class DSU:     def __init__(self, n):         self.parent = list(range(n))         self.rank = [1] * n      def find(self, i):         if self.parent[i] != i:             self.parent[i] = self.find(self.parent[i])         return self.parent[i]      def union(self, x, y):         s1 = self.find(x)         s2 = self.find(y)         if s1 != s2:             if self.rank[s1] < self.rank[s2]:                 self.parent[s1] = s2             elif self.rank[s1] > self.rank[s2]:                 self.parent[s2] = s1             else:                 self.parent[s2] = s1                 self.rank[s1] += 1   if __name__ == '__main__':          # An edge contains, weight, source and destination     edges = [[0, 1, 10], [1, 3, 15], [2, 3, 4], [2, 0, 6], [0, 3, 5]]     print(kruskals_mst(4, edges)) 
C#
// Using System.Collections.Generic; using System;  class GfG {     public static int KruskalsMST(int V, int[][] edges) {         // Sort all edges based on weight         Array.Sort(edges, (e1, e2) => e1[2].CompareTo(e2[2]));                  // Traverse edges in sorted order         DSU dsu = new DSU(V);         int cost = 0, count = 0;                  foreach (var e in edges) {             int x = e[0], y = e[1], w = e[2];                          // Make sure that there is no cycle             if (dsu.Find(x) != dsu.Find(y)) {                 dsu.Union(x, y);                 cost += w;                 if (++count == V - 1) break;             }         }         return cost;     }      public static void Main(string[] args) {         // An edge contains, weight, source and destination         int[][] edges = {             new int[] {0, 1, 10}, new int[] {1, 3, 15}, new int[] {2, 3, 4}, new int[] {2, 0, 6}, new int[] {0, 3, 5}         };                  Console.WriteLine(KruskalsMST(4, edges));     } }  // Disjoint set data structure class DSU {     private int[] parent, rank;      public DSU(int n) {         parent = new int[n];         rank = new int[n];         for (int i = 0; i < n; i++) {             parent[i] = i;             rank[i] = 1;         }     }      public int Find(int i) {         if (parent[i] != i) {             parent[i] = Find(parent[i]);         }         return parent[i];     }      public void Union(int x, int y) {         int s1 = Find(x);         int s2 = Find(y);         if (s1 != s2) {             if (rank[s1] < rank[s2]) {                 parent[s1] = s2;             } else if (rank[s1] > rank[s2]) {                 parent[s2] = s1;             } else {                 parent[s2] = s1;                 rank[s1]++;             }         }     } } 
JavaScript
function kruskalsMST(V, edges) {          // Sort all edges     edges.sort((a, b) => a[2] - b[2]);          // Traverse edges in sorted order     const dsu = new DSU(V);     let cost = 0;     let count = 0;     for (const [x, y, w] of edges) {                  // Make sure that there is no cycle         if (dsu.find(x) !== dsu.find(y)) {             dsu.unite(x, y);             cost += w;             if (++count === V - 1) break;         }     }     return cost; }  // Disjoint set data structure class DSU {     constructor(n) {         this.parent = Array.from({ length: n }, (_, i) => i);         this.rank = Array(n).fill(1);     }      find(i) {         if (this.parent[i] !== i) {             this.parent[i] = this.find(this.parent[i]);         }         return this.parent[i];     }      unite(x, y) {         const s1 = this.find(x);         const s2 = this.find(y);         if (s1 !== s2) {             if (this.rank[s1] < this.rank[s2]) this.parent[s1] = s2;             else if (this.rank[s1] > this.rank[s2]) this.parent[s2] = s1;             else {                 this.parent[s2] = s1;                 this.rank[s1]++;             }         }     } }  const edges = [     [0, 1, 10], [1, 3, 15], [2, 3, 4], [2, 0, 6], [0, 3, 5] ]; console.log(kruskalsMST(4, edges)); 

Output
Following are the edges in the constructed MST 2 -- 3 == 4 0 -- 3 == 5 0 -- 1 == 10 Minimum Cost Spanning Tree: 19 

Time Complexity: O(E * log E) or O(E * log V) 

  • Sorting of edges takes O(E*logE) time. 
  • After sorting, we iterate through all edges and apply the find-union algorithm. The find and union operations can take at most O(logV) time.
  • So overall complexity is O(E*logE + E*logV) time. 
  • The value of E can be at most O(V2), so O(logV) and O(logE) are the same. Therefore, the overall time complexity is O(E * logE) or O(E*logV)

Auxiliary Space: O(E+V), where V is the number of vertices and E is the number of edges in the graph.

Problems based on Minimum Spanning Tree

  • Prim’s Algorithm for MST
  • Minimum cost to connect all cities
  • Minimum cost to provide water
  • Second Best Minimum Spanning Tree
  • Check if an edge is a part of any MST
  • Minimize count of connections


Next Article
Difference between Prim's and Kruskal's algorithm for MST
author
kartik
Improve
Article Tags :
  • DSA
  • Graph
  • Greedy
  • Kruskal
  • Kruskal'sAlgorithm
  • MST
Practice Tags :
  • Graph
  • Greedy

Similar Reads

  • Graph Algorithms
    Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. BasicsGraph and its representationsBFS and DFS Breadt
    3 min read
  • Introduction to Graph Data Structure
    Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
    15+ min read
  • Graph and its representations
    A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
    12 min read
  • Types of Graphs with Examples
    A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
    9 min read
  • Basic Properties of a Graph
    A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are kn
    4 min read
  • Applications, Advantages and Disadvantages of Graph
    Graph is a non-linear data structure that contains nodes (vertices) and edges. A graph is a collection of set of vertices and edges (formed by connecting two vertices). A graph is defined as G = {V, E} where V is the set of vertices and E is the set of edges. Graphs can be used to model a wide varie
    7 min read
  • Transpose graph
    Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Giv
    9 min read
  • Difference Between Graph and Tree
    Graphs and trees are two fundamental data structures used in computer science to represent relationships between objects. While they share some similarities, they also have distinct differences that make them suitable for different applications. What is Graph?A graph data structure is a collection o
    2 min read
  • BFS and DFS on Graph

    • Breadth First Search or BFS for a Graph
      Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
      15+ min read

    • Depth First Search or DFS for a Graph
      In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
      13 min read

    • Applications, Advantages and Disadvantages of Depth First Search (DFS)
      Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
      4 min read

    • Applications, Advantages and Disadvantages of Breadth First Search (BFS)
      We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
      4 min read

    • Iterative Depth First Traversal of Graph
      Given a directed Graph, the task is to perform Depth First Search of the given graph. Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list. Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pic
      10 min read

    • BFS for Disconnected Graph
      In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
      14 min read

    • Transitive Closure of a Graph using DFS
      Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: Transit
      8 min read

    • Difference between BFS and DFS
      Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS st
      2 min read

    Cycle in a Graph

    • Detect Cycle in a Directed Graph
      Given the number of vertices V and a list of directed edges, determine whether the graph contains a cycle or not. Examples: Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 0 Input: V = 4, edges[][] = [[0, 1], [0, 2
      15+ min read

    • Detect cycle in an undirected graph
      Given an undirected graph, the task is to check if there is a cycle in the given graph. Examples: Input: V = 4, edges[][]= [[0, 1], [0, 2], [1, 2], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0 Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]] Output: falseExplana
      8 min read

    • Detect Cycle in a directed graph using colors
      Given a directed graph represented by the number of vertices V and a list of directed edges, determine whether the graph contains a cycle. Your task is to implement a function that accepts V (number of vertices) and edges (an array of directed edges where each edge is a pair [u, v]), and returns tru
      9 min read

    • Detect a negative cycle in a Graph | (Bellman Ford)
      Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directe
      15+ min read

    • Cycles of length n in an undirected and connected graph
      Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
      10 min read

    • Detecting negative cycle using Floyd Warshall
      We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative. Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some adva
      12 min read

    • Clone a Directed Acyclic Graph
      A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
      12 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences