Kruskal's Algorithm

Graph Selection

Playback Controls

Select a graph to begin MST visualization

Kruskal's Info

Key Features:

  • • Finds Minimum Spanning Tree
  • • Uses greedy approach
  • • Time complexity: O(E log E)
  • • Uses Union-Find data structure
  • • Avoids cycles in the tree

Legend:

Current Edge
MST Edges
Connected Components

Reference implementation of Kruskal's Algorithm. Select a language tab to view and copy the code.

def kruskal(n: int, edges: list[tuple[int,int,int]]) -> int:
    parent = list(range(n))
    rank   = [0] * n

    def find(x: int) -> int:
        if parent[x] != x:
            parent[x] = find(parent[x])   # path compression
        return parent[x]

    def union(x: int, y: int) -> bool:
        px, py = find(x), find(y)
        if px == py: return False
        if rank[px] < rank[py]: px, py = py, px
        parent[py] = px
        if rank[px] == rank[py]: rank[px] += 1
        return True

    edges.sort(key=lambda e: e[2])
    mst_weight = 0
    for u, v, w in edges:
        if union(u, v):
            mst_weight += w
    return mst_weight

Python — Code Walkthrough

  1. Nested functions share closure over parent/rank

    def find(x) ... def union(x, y) ...

    Python nested functions capture parent and rank from the enclosing scope by reference (closure). This avoids passing them as parameters on every call, keeping the signatures clean.

  2. list(range(n)) initialises parent[i] = i

    parent = list(range(n))

    range(n) generates 0, 1, …, n−1. Converting to list creates an editable copy. This is the most Pythonic way to initialise the Union-Find parent array.

  3. Sort by third element of each tuple

    edges.sort(key=lambda e: e[2])

    key=lambda e: e[2] extracts the weight from each (u, v, weight) edge tuple. sort is in-place, stable, and uses Timsort — O(E log E).

  4. union returns bool — used in if

    if union(u, v): mst_weight += w

    union returns True only when u and v were in different components. Returning False for same-component merges keeps the main loop free of an explicit find-comparison.