VOOZH about

URL: https://www.geeksforgeeks.org/python/kruskals-algorithm-in-python/

⇱ Kruskal's Algorithm in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kruskal's Algorithm in Python

Last Updated : 23 Jul, 2025

Kruskal’s Algorithm is a greedy algorithm used to find MST in the graph. A minimum spanning tree (MST) is a spanning tree with a weight less than or equal to the weight of every other spanning tree. Kruskal’s Algorithm sorts 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 and therefore it is a greedy algorithm. The Greedy Choice is to pick the smallest weight edge that does not cause a cycle in the MST constructed so far.

Examples:

Input: N = 6, edges[][] = {{1, 2, 1}, {2, 3, 4}, {1, 4, 3}, {4, 5, 6}, {2, 5, 2}, {3, 5, 5}, {5, 6, 6}}
Output: MST with edges: {{1, 2, 1}, {2, 3, 4}, {1, 4, 3}, {2, 5, 2}, {5, 6, 6}}

👁 MST
Kruskal's Algorithm

Step-by-step algorithm:

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

Implementation of Kruskal's Algorithm in Python:

Below is the implementation of Kruskal's Algorithm in Python:


Output
Edges in the constructed MST
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Spanning Tree 19

Time Complexity: O(E * logE) or O(E * logV) 
Auxiliary Space: O(V + E), where V is the number of vertices and E is the number of edges in the graph.

Comment
Article Tags: