Minimum Spanning Tree (Kruskal's Algorithm)
Software Engineer path · lesson 28 of 99Visualize Kruskal's MST algorithm: sort all edges by weight, then greedily add the cheapest edges that don't create a cycle using Union-Find. Demonstrates why a greedy approach guarantees a minimum spanning tree on connected graphs.
Like A-B 4, separated by commas. Up to 9 nodes.
Both find the same total weight.
Sort the 7 edges by weight: 1, 2, 3, 4, 5, 6, 7.
- 1sort edges by weight
- 2for (u, v, w) in sorted edges:
- 3 if find(u) != find(v): # different components
- 4 take the edge; union(u, v)
- 5 else: skip — it would close a cycle
- 6stop when n - 1 edges are taken
- Edges examined
- 0 / 5
- Edges taken
- 0 / 4
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Kruskal’s algorithm
Order the steps of building a minimum spanning tree.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
When is Kruskal preferred over Prim?
The short version
Imagine connecting all houses in a neighborhood with water pipes. You want to use the minimum total pipe length while ensuring every house gets water. MST finds the cheapest way to connect everyone.
In more depth
Two Approaches
Kruskal's Algorithm:
Prim's Algorithm:
When to Use:
Key Gotchas:
When to reach for this
- Connect all nodes with minimum total edge weight
- Network/cable/pipe laying problems
- Keywords: 'minimum cost to connect', 'spanning tree'
- Any graph edge selection with global minimum goal
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required