Practice GFG · Kruskal's MST · LeetCode 1584 · Min Cost to Connect Points
GraphsGreedyMSTUnion-Find

Kruskal's · Minimum Spanning Tree

Connect every node at minimum total cost. Kruskal's sorts all edges cheapest-first and greedily adds each one, unless it would form a cycle. Union-Find is the cycle referee.

The greedy idea

Sort edges by weight ascending. Walk them cheapest-first: if an edge joins two different components, take it (union them). If both ends are already connected, it'd make a cycle, skip it.

Union-Find's role

  • Each node starts in its own set
  • find(x) returns x's component root
  • Same root on both ends → cycle → skip
  • Stop once you've added V-1 edges

Pick edges cheapest-first

Unused edge Considering In MST Skipped (cycle)
slowfast
Step 0
MST edges
0
Total cost
0
Skipped
0
Components
–

C++

int parent[MAXN], rnk[MAXN];
int find(int x) { return parent[x] == x ? x : parent[x] = find(parent[x]); }
bool unite(int a, int b) {
    a = find(a); b = find(b);
    if (a == b) return false;         // same set → cycle
    if (rnk[a] < rnk[b]) swap(a, b);
    parent[b] = a;
    if (rnk[a] == rnk[b]) rnk[a]++;
    return true;
}

int kruskal(int n, vector<array<int,3>>& edges) {
    for (int i = 0; i < n; i++) parent[i] = i, rnk[i] = 0;
    sort(edges.begin(), edges.end(),        // by weight ascending
         [](auto& a, auto& b){ return a[2] < b[2]; });

    int cost = 0, used = 0;
    for (auto& [w, u, v] : edges) {
        if (unite(u, v)) {              // joins two components
            cost += w; used++;
            if (used == n - 1) break;   // MST complete
        }
    }
    return cost;
}
Time
O(E log E)

Dominated by sorting the edges. Union-Find ops are near-constant.

Space
O(V)

Parent and rank arrays for the disjoint-set structure.

Stops at
V − 1

A spanning tree of V nodes has exactly V-1 edges.

  • Kruskal vs Prim: Kruskal is edge-centric (sort + union), great for sparse graphs. Prim is node-centric (grow one tree), better for dense ones.
  • Union by rank + path compression makes find/unite effectively O(α(n)), basically constant.
  • If you never reach V-1 edges, the graph is disconnected, no spanning tree exists (you get a spanning forest).
  • MST isn't always unique, equal-weight edges can yield different valid trees.
  • Min Cost to Connect Points is Kruskal on a complete graph of Manhattan-distance edges.