Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the key values for all vertices in Prim's algorithm.
DSA C++
for (int i = 0; i < V; i++) { key[i] = [1]; mstSet[i] = false; }
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing key values to 0 causes incorrect minimum edge selection.
Using negative values for key leads to wrong comparisons.
✗ Incorrect
In Prim's algorithm, key values are initialized to a very large number (infinity) to ensure any edge weight will be smaller.
2fill in blank
mediumComplete the code to find the vertex with the minimum key value not yet included in MST.
DSA C++
int minKey(int key[], bool mstSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (mstSet[v] == false && key[v] < [1]) {
min = key[v];
min_index = v;
}
}
return min_index;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing key[v] with v instead of min causes wrong minimum selection.
Using mstSet[v] in comparison leads to logical errors.
✗ 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 updating key and parent arrays inside the main loop of Prim's algorithm.
DSA C++
for (int v = 0; v < V; v++) { if (graph[u][v] && mstSet[v] == false && graph[u][v] < [1]) { parent[v] = u; key[v] = graph[u][v]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with parent[v] instead of key[v] causes wrong updates.
Using graph[u][v] < graph[u][v] is always false.
✗ Incorrect
We update the key[v] only if the new edge weight graph[u][v] is less than the current key[v].
4fill in blank
hardFill both blanks to complete the loop that constructs the MST result output.
DSA C++
for (int i = 1; i < V; i++) { cout << parent[i] << " - " << [1] << " \t" << [2] << endl; }
Attempts:
3 left
💡 Hint
Common Mistakes
Printing parent[i] twice instead of i.
Using key[i] instead of graph[parent[i]][i] for weight.
✗ Incorrect
We print the edge from parent[i] to i and its weight graph[parent[i]][i].
5fill in blank
hardFill all three blanks to complete the main Prim's algorithm function header and initialization.
DSA C++
void primMST([1] graph[[2]][[2]]) { int parent[[2]]; int key[[2]]; bool mstSet[[2]];
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'const int' in function parameter causes syntax issues here.
Using 'size' instead of V leads to undefined variable errors.
✗ Incorrect
The function takes an int 2D array graph of size VxV; arrays parent, key, mstSet are sized by V.
