Data Structures · Visualization
Graph: Kruskal MST
Graph
Kruskal's algorithm builds a Minimum Spanning Tree (MST) — a subset of edges that connects every node together using the least total edge weight possible, with no cycles. Time: O(E log E) for sorting edges, dominated by the sort. Space: O(V) for the Union-Find structure.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Kruskal MST
GraphKruskal's algorithm builds a Minimum Spanning Tree (MST) — a subset of edges that connects every node together using the least total edge weight possible, with no cycles. It works greedily by sorting all edges from cheapest to most expensive, then adding each edge one at a time, skipping any edge that would create a cycle (checked efficiently using a Disjoint Set / Union-Find structure), until all nodes are connected.
How Kruskal MST Works
- Sort all edges in the graph by weight, from smallest to largest.
- Start with no edges selected and every node in its own separate group (Union-Find).
- Go through the sorted edges one by one; for each edge, check if its two endpoints are already in the same group.
- If they are in different groups, add the edge to the MST and merge the two groups; if they're already in the same group, skip it (it would create a cycle).
- Stop once V-1 edges have been added (enough to connect all V nodes).
Kruskal MST Worked Example
Input: Edges (sorted by weight): B-C(1), A-C(2), A-B(3)
- Add B-C(1): B and C were separate, merge them
- Add A-C(2): A and C were separate, merge them (now A, B, C all connected)
- Consider A-B(3): A and B are already in the same group — skip (would create a cycle)
Output: MST edges: B-C, A-C (total weight 3)
Press ▶ Run to watch it step by step.
def kruskal(vertices, edges):
parent = {v: v for v in vertices}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
mst = []
for a, b, w in sorted(edges, key=lambda e: e[2]):
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb # union
mst.append((a, b, w))
return mst
# example: Kruskal MSTBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Kruskal MST Time & Space Complexity
When to Use Kruskal MST
- Designing a minimum-cost network (e.g. laying cable to connect cities cheaply)
- Circuit design, minimizing wiring cost
- Clustering algorithms that use MST as a building block
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.