Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get the index of the last non-leaf node in the heap array.
DSA C++
int lastNonLeaf = (n [1] 2) - 1;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of division.
Forgetting to subtract 1 after division.
✗ Incorrect
The last non-leaf node in a heap array of size n is at index (n / 2) - 1.
2fill in blank
mediumComplete the code to call heapify on each non-leaf node starting from the last non-leaf node.
DSA C++
for (int i = lastNonLeaf; i >= 0; i--) { heapify(arr, n, [1]); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the size n instead of the node index.
Passing 0 or lastNonLeaf instead of the current index.
✗ Incorrect
We call heapify on each node index i from lastNonLeaf down to 0.
3fill in blank
hardFix the error in the heapify function call inside the buildHeap function.
DSA C++
void buildHeap(int arr[], int n) {
int startIdx = (n / 2) - 1;
for (int i = startIdx; i >= 0; i--) {
heapify(arr, [1], i);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the current index i as the size parameter.
Confusing the order of parameters in heapify.
✗ Incorrect
heapify needs the size of the array n and the current index i to work correctly.
4fill in blank
hardFill both blanks to complete the heapify function's left and right child index calculations.
DSA C++
int left = 2 * [1] + [2]; int right = 2 * [1] + 2;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of 1 for left child offset.
Using n or other variables instead of i.
✗ Incorrect
Left child index is 2*i + 1 and right child index is 2*i + 2 in a zero-indexed heap array.
5fill in blank
hardFill all three blanks to complete the heapify function's swap and recursive call.
DSA C++
if (largest != [1]) { std::swap(arr[[2]], arr[[3]]); heapify(arr, n, largest); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping wrong indices.
Not calling heapify recursively after swap.
✗ Incorrect
We swap arr[i] with arr[largest] and then call heapify on largest to fix the subtree.