DrawCode Algorithm Visualizer • Graph • Medium

Kruskal's Algorithm (MST)

Tags: Graph, MST, Greedy, Union-Find

1. One-Liner

Kruskal sorts all edges by weight and adds the next lightest edge if it connects two different components (union-find detects cycles).


2. The Problem It Solves

Same as Prim: minimum spanning tree for a connected undirected weighted graph — often easier to implement with DSU on sparse graphs.


3. The Core Idea

Cut property / Kruskal: processing edges lightest-first, an edge is safe iff it does not close a cycle in the forest built so far.


4. How It Works (Step-by-Step)

StepAction
1Sort edges by weight ascending
2Initialize DSU with V singleton sets
3For each edge (u,v,w): if find(u)≠find(v), union and add w to total
4Stop after V−1 edges added

5. Dry Run Example

Edges: (0,1,1), (1,2,2), (0,2,5). Take 0–1, then 1–2, skip 0–2 (cycle). Total 3.


6. Key Properties

PropertyValue
Disjoint setsPath compression + union by rank → α(V) amortized
Edge-centricNatural for sparse E

7. Where It Is Used

DomainUse
Same as PrimNetwork design, image segmentation (graph cuts related)
Kaggle / MLClustering approximations

8. Interview Tips

Implement DSU cleanly; prove cycle avoidance equals cut optimality. Compare time vs Prim.


9. Comparison with Other Algorithms

KruskalPrim
SortO(E log E)No global sort
DSUYesNo
SparseOften winsDense graph alternative

10. Complexity

----
TimeO(E log E) for sort + O(E α(V)) for DSU
SpaceO(V + E)

Implementation Example (PYTHON)

def kruskal(n, edges):
    parent = list(range(n))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    def union(a, b):
        ra, rb = find(a), find(b)
        if ra == rb: return False
        parent[rb] = ra
        return True
    edges = sorted(edges, key=lambda e: e[2])
    total = 0
    for u, v, w in edges:
        if union(u, v):
            total += w
    return total

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer