const edges = [
{u: 0, v: 1, w: 10},
{u: 0, v: 2, w: 6},
{u: 0, v: 3, w: 5},
{u: 1, v: 3, w: 15},
{u: 2, v: 3, w: 4}
];
// Kruskal's algorithm picks edges in ascending order of weight
// and adds them if they don't form a cycle.
// What edges are in the MST (list of [u,v])?
// Output format: JSON array of edges, e.g. [[0,3],[2,3],[0,1]]Kruskal's algorithm sorts edges by weight: (2,3)=4, (0,3)=5, (0,2)=6, (0,1)=10, (1,3)=15.
It picks (2,3), then (0,3), then (0,2) would form a cycle, so skip it, then (0,1) is safe.
Edges in MST: (2,3), (0,3), (0,1).
The disjoint set helps track which nodes are connected.
Before adding an edge, it checks if the two nodes belong to the same set.
If yes, adding the edge creates a cycle, so it is skipped.
function find(parent, i) {
if (parent[i] === i) return i;
return find(parent, parent[i]);
}
function union(parent, rank, x, y) {
let xroot = find(parent, x);
let yroot = find(parent, y);
if (rank[xroot] < rank[yroot]) {
parent[xroot] = yroot;
} else if (rank[xroot] > rank[yroot]) {
parent[yroot] = xroot;
} else {
parent[yroot] = xroot;
rank[xroot]++;
}
}
// Missing initialization of parent and rank arrays
const edges = [
{u: 0, v: 1, w: 1},
{u: 1, v: 2, w: 2}
];
// Attempt to run union-find without initializing parent and rank
union(parent, rank, 0, 1);The code calls union(parent, rank, 0, 1) but parent and rank are never declared or initialized.
This causes a ReferenceError because parent is undefined.
const edges = [
{u: 0, v: 1, w: 4},
{u: 0, v: 2, w: 3},
{u: 1, v: 2, w: 1},
{u: 1, v: 3, w: 2},
{u: 2, v: 3, w: 4},
{u: 3, v: 4, w: 2},
{u: 4, v: 5, w: 6}
];
// MST weight is sum of selected edges' weightsEdges sorted by weight: (1,2)=1, (1,3)=2, (3,4)=2, (0,2)=3, (0,1)=4, (2,3)=4, (4,5)=6.
Pick (1,2), (1,3), (3,4), (0,2), (4,5) without cycles.
Total weight = 1+2+2+3+6 = 14, but (0,1) or (2,3) would create cycles.
Actually, MST edges: (1,2), (1,3), (3,4), (0,2), (4,5) sum to 14.
But we must check carefully: (0,2) connects 0 and 2, (1,2) connects 1 and 2, (1,3) connects 1 and 3, (3,4) connects 3 and 4, (4,5) connects 4 and 5.
Sum is 1+2+2+3+6=14.
But option D is 10, so re-check.
Actually, (4,5) weight 6 is large, maybe we can avoid it?
Graph has 6 nodes (0 to 5), MST must have 5 edges.
Edges chosen: (1,2)=1, (1,3)=2, (3,4)=2, (0,2)=3, (4,5)=6 total 14.
So correct answer is 14.
Kruskal's algorithm sorts all edges by weight.
Sparse graphs have fewer edges, so sorting is faster.
Also, fewer edges mean fewer union-find operations.
