Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the Edge class with weight attribute.
DSA Java
class Edge implements Comparable<Edge> { int src, dest, weight; Edge(int s, int d, int w) { src = s; dest = d; [1] = w; } public int compareTo(Edge other) { return this.weight - other.weight; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to the wrong variable like 'dest = w;'
Using the parameter name instead of the instance variable
✗ Incorrect
The constructor assigns the parameter w to the instance variable weight.
2fill in blank
mediumComplete the code to initialize the parent array for union-find.
DSA Java
int[] parent = new int[V]; for (int i = 0; i < V; i++) { parent[i] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting all parents to i or 0 which breaks union-find logic
✗ Incorrect
Each vertex is initially its own parent, so parent[i] = -1.
3fill in blank
hardFix the error in the find method to correctly find the root parent.
DSA Java
int find(int[] parent, int i) {
if (parent[i] == [1]) {
return i;
}
return find(parent, parent[i]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking parent[i] == i which is incorrect for this union-find implementation
✗ Incorrect
In union-find, root parents have parent[i] == -1.
4fill in blank
hardFill both blanks to correctly perform union operation.
DSA Java
void union(int[] parent, int x, int y) {
int xset = find(parent, x);
int yset = find(parent, y);
if (xset != yset) {
parent[[1]] = [2];
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using x or y instead of root parents xset or yset
Assigning parent[yset] = xset instead of parent[xset] = yset (both valid but must be consistent)
✗ Incorrect
Union sets by making one root parent point to the other root parent.
5fill in blank
hardFill all three blanks to complete the Kruskal's algorithm loop for MST.
DSA Java
int e = 0; // count of edges in MST int i = 0; // index for sorted edges while (e < V - 1 && i < edges.length) { Edge nextEdge = edges[[1]]; int x = find(parent, nextEdge.src); int y = find(parent, nextEdge.dest); if (x != y) { union(parent, x, y); mstEdges[[2]] = nextEdge; e[3]; } i++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices for arrays
Decrementing e instead of incrementing
✗ Incorrect
Use i to index edges, e to index MST edges, and increment e after adding an edge.
