interface Edge {
src: number;
dest: number;
weight: number;
}
const edges: Edge[] = [
{src: 0, dest: 1, weight: 10},
{src: 0, dest: 2, weight: 6},
{src: 0, dest: 3, weight: 5},
{src: 1, dest: 3, weight: 15},
{src: 2, dest: 3, weight: 4}
];
// After running Kruskal's MST, print edges in MST as array of [src, dest]
// in the order they are added.
// Assume vertices are 0 to 3.Kruskal's algorithm sorts edges by weight: (2,3)=4, (0,3)=5, (0,2)=6, (0,1)=10, (1,3)=15.
Pick edges in this order if they don't form a cycle:
- (2,3) weight 4 - add
- (0,3) weight 5 - add
- (0,2) weight 6 - would form cycle with (2,3) and (0,3), skip
- (0,1) weight 10 - add
- (1,3) weight 15 - would form cycle, skip
Edges in MST: (2,3), (0,3), (0,1)
An MST connects all vertices with the minimum number of edges to avoid cycles.
For V vertices, MST always has exactly V - 1 edges.
class DisjointSet { parent: number[]; constructor(n: number) { this.parent = Array(n).fill(-1); } find(x: number): number { if (this.parent[x] < 0) return x; return this.find(this.parent[x]); } union(a: number, b: number): void { const rootA = this.find(a); const rootB = this.find(b); if (rootA !== rootB) { this.parent[rootB] = rootA; } } } // Usage omitted for brevity
The find() method uses recursion but does not update parent[x] to root, so deep recursion can cause stack overflow.
This is a common issue without path compression optimization.
const edges = [
{src: 0, dest: 1, weight: 7},
{src: 0, dest: 3, weight: 5},
{src: 1, dest: 2, weight: 8},
{src: 1, dest: 3, weight: 9},
{src: 1, dest: 4, weight: 7},
{src: 2, dest: 4, weight: 5},
{src: 3, dest: 4, weight: 15},
{src: 3, dest: 5, weight: 6},
{src: 4, dest: 5, weight: 8},
{src: 4, dest: 6, weight: 9},
{src: 5, dest: 6, weight: 11}
];
// Cities numbered 0 to 6
// Calculate total weight of MSTSorted edges by weight: (0,3)=5, (2,4)=5, (3,5)=6, (0,1)=7, (1,4)=7, (1,2)=8, (4,5)=8, (1,3)=9, (4,6)=9, (5,6)=11, (3,4)=15.
Pick edges in this order if they don't form a cycle:
- (0,3) weight 5 - add
- (2,4) weight 5 - add
- (3,5) weight 6 - add
- (0,1) weight 7 - add
- (1,4) weight 7 - add (connects {0,1,3,5} and {2,4})
- (1,2) weight 8 - cycle, skip
- (4,5) weight 8 - cycle, skip
- (1,3) weight 9 - cycle, skip
- (4,6) weight 9 - add
Edges in MST: (0,3), (2,4), (3,5), (0,1), (1,4), (4,6)
Total weight = 5 + 5 + 6 + 7 + 7 + 9 = 39
const edges = [
{src: 0, dest: 1, weight: 4},
{src: 1, dest: 2, weight: 8},
{src: 2, dest: 3, weight: 7},
];
edges.sort((a, b) => a.weight - b.weight)
for (const edge of edges) {
if (disjointSet.find(edge.src) !== disjointSet.find(edge.dest)) {
disjointSet.union(edge.src, edge.dest)
mstEdges.push(edge)
}
}The code uses disjointSet without declaring or initializing it, causing a ReferenceError.
Missing semicolons or arrow function braces are not syntax errors in this context.
mstEdges usage without declaration would also cause error, but question focuses on disjointSet.