1. Sort by weight
Process the cheapest edges first so each pick is the best available.
edges.sort((a, b) => a[2] - b[2])Typorithm · medium
Step 1 of 8 · intro card
Graph Algorithms
Sort edges by weight, then greedily add each edge whose endpoints are in different sets via Union-Find, stopping at n-1 edges.
Kruskal's builds a minimum spanning tree by considering edges from cheapest to most expensive.
A Union-Find structure answers whether two endpoints already sit in the same component.
An edge is kept only if union joins two different sets — that guarantees no cycle forms.
Sort all edges by weight ascending.
union returns true = different sets, so add the edge.
Stop once n-1 edges are chosen.
function kruskalMst(n, edges) {
edges.sort((a, b) => a[2] - b[2]);
const dsu = new UnionFind(n);
let total = 0;
let used = 0;
const tree = [];
for (const [a, b, weight] of edges) {
if (dsu.union(a, b)) {
tree.push([a, b, weight]);
total += weight;
used += 1;
if (used === n - 1) break;
}
}
return used === n - 1 ? { total, tree } : null;
}Connect each part of the code to the concept before you type.
Process the cheapest edges first so each pick is the best available.
edges.sort((a, b) => a[2] - b[2])Each node starts in its own set; the DSU tracks which nodes are connected.
const dsu = new UnionFind(n)union returns true only when the endpoints were in different sets, so adding the edge cannot form a cycle.
if (dsu.union(a, b))A safe edge joins two components and belongs in the spanning tree.
tree.push([a, b, weight])A spanning tree on n nodes has exactly n-1 edges, so we can stop early.
if (used === n - 1) breakRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputUndirected graph · start A · edges A–B:4, A–D:2, B–C:3, B–E:1, D–E:5, E–F:2, C–F:4
Follow temporary values, local state and supporting structures at this step.
parents6 entries
selected edges0 entries
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state