Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the key array with maximum values.
DSA Java
int[] key = new int[V]; for (int i = 0; i < V; i++) { key[i] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing key with 0 causes incorrect minimum edge selection.
Using negative values can cause logic errors.
✗ Incorrect
We initialize the key array with Integer.MAX_VALUE to represent infinite distance before updating with actual edge weights.
2fill in blank
mediumComplete the code to pick the vertex with the minimum key value not yet included in MST.
DSA Java
int minKey(int[] key, boolean[] mstSet) {
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++) {
if (!mstSet[v] && key[v] < [1]) {
min = key[v];
min_index = v;
}
}
return min_index;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing key[v] with Integer.MAX_VALUE inside the loop always true for first iteration but not updated later.
Using min_index instead of min causes type mismatch.
✗ Incorrect
We compare key[v] with the current minimum value stored in min to find the smallest key.
3fill in blank
hardFix the error in the loop that updates key values for adjacent vertices.
DSA Java
for (int v = 0; v < V; v++) { if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < [1]) { parent[v] = u; key[v] = graph[u][v]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with key[u] causes wrong logic since key[u] is for the selected vertex.
Using parent array in comparison causes type errors.
✗ Incorrect
We compare the edge weight graph[u][v] with key[v] to update the minimum edge weight for vertex v.
4fill in blank
hardFill both blanks to complete the code that prints the MST edges and their weights.
DSA Java
void printMST(int[] parent, int[][] graph) {
System.out.println("Edge \tWeight");
for (int i = 1; i < V; i++) {
System.out.println(parent[i] + " - " + [1] + " \t" + [2]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping i and parent[i] in graph indexing causes wrong weights.
Printing parent[i] twice instead of i causes incorrect output.
✗ Incorrect
We print the edge from parent[i] to i and the weight from graph[parent[i]][i].
5fill in blank
hardFill all three blanks to complete the main loop of Prim's algorithm updating MST and keys.
DSA Java
for (int count = 0; count < V - 1; count++) { int u = [1](key, mstSet); mstSet[u] = true; for (int v = 0; v < V; v++) { if (graph[u][v] != 0 && ![3] && graph[u][v] < [2]) { parent[v] = u; key[v] = graph[u][v]; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using key[u] instead of key[v] in comparison.
Not checking mstSet[v] causes revisiting vertices.
✗ Incorrect
We pick the vertex u with minimum key using minKey, then update key[v] if graph[u][v] is smaller than key[v] and v is not in mstSet.
