#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Graph Algorithms

Spanning Tree and Minimum Spanning Tree — Kruskal's and Prim's Algorithm

A Spanning Tree of a connected, undirected graph is a subgraph that includes all the vertices with the minimum number of edges needed to keep the graph connected, and without forming any cycles. A Minimum Spanning Tree (MST) is a spanning tree with the smallest possible total edge weight.

Kruskal's Algorithm

Kruskal's builds the MST by sorting all edges by weight and adding them one at a time, skipping any edge that would form a cycle (checked using a Union-Find/Disjoint Set structure), until all vertices are connected.

def kruskal(num_vertices, edges):
    parent = list(range(num_vertices))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    def union(x, y):
        parent[find(x)] = find(y)

    mst = []
    for u, v, w in sorted(edges, key=lambda e: e[2]):
        if find(u) != find(v):
            union(u, v)
            mst.append((u, v, w))
    return mst

Prim's Algorithm

Prim's builds the MST by starting from an arbitrary vertex and repeatedly adding the cheapest edge that connects a vertex already in the MST to a vertex outside it, typically using a priority queue.

import heapq

def prim(num_vertices, adj):
    visited = [False] * num_vertices
    min_heap = [(0, 0)]   # (weight, vertex)
    total_cost = 0

    while min_heap:
        weight, u = heapq.heappop(min_heap)
        if visited[u]:
            continue
        visited[u] = True
        total_cost += weight
        for v, w in adj[u]:
            if not visited[v]:
                heapq.heappush(min_heap, (w, v))
    return total_cost

Complexity

AlgorithmTime Complexity
Kruskal's (with Union-Find)O(E log E)
Prim's (with binary heap)O(E log V)

Applications

  • Network design — laying cables or pipelines at minimum cost.
  • Approximation algorithms for problems like the Traveling Salesman Problem.
  • Cluster analysis in machine learning.

Why Both Algorithms Give a Valid MST

Kruskal's and Prim's look different but both rely on the same guarantee, the cut property. It says that for any way of splitting the vertices into two groups, the cheapest edge crossing the split is safe to include in some minimum spanning tree. Kruskal's applies this globally — it always grabs the next cheapest edge anywhere, as long as it does not close a cycle. Prim's applies it locally — it always grabs the cheapest edge leaving the tree built so far. Because every edge they add is a safe edge, both finish with a tree of minimum total weight.

Kruskal vs Prim: Which Fits Your Graph

FactorKruskal'sPrim's
Works onEdge list, sorted by weightAdjacency list with a heap
StrengthSparse graphs (few edges)Dense graphs (many edges)
Core helperUnion-Find (disjoint set)Priority queue
GrowsA forest that merges into one treeOne tree outward from a start vertex

For a sparse graph where edges are easy to list and sort, Kruskal's is natural. For a dense graph where a vertex connects to many others, Prim's with a heap tends to win. Both land near O(E log V), so the choice is usually about which structure your input already fits.

The Cut Property in Plain Words

Picture the vertices divided into "inside the tree" and "outside". Among all the roads connecting the two sides, the cheapest one can never be a mistake — leaving it out and using a pricier crossing would only raise the total. That is the intuition behind why greedily taking the cheapest safe edge keeps working all the way to a complete minimum tree.

  • A spanning tree of n vertices always has exactly n - 1 edges and no cycles.
  • The graph must be connected for a single spanning tree to exist; otherwise you get a spanning forest.
  • In Kruskal's, the Union-Find structure is what detects a cycle quickly before an edge is added.

Takeaway: both algorithms are greedy and both are correct because every edge they add is justified by the cut property. Choose Kruskal's for sparse, edge-listed graphs and Prim's for dense ones, and remember the n - 1 edge rule as a quick sanity check.