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 Typescript
const lastNonLeaf = Math.floor((arr.length - 2) / [1]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using length / 2 instead of (length - 2) / 2
Using 3 instead of 2 as divisor
Confusing leaf nodes with non-leaf nodes
✗ Incorrect
In a binary heap stored as an array, the last non-leaf node is at index floor((n-2)/2).
2fill in blank
mediumComplete the code to swap two elements in the array during heapify.
DSA Typescript
const temp = arr[i]; arr[i] = arr[[1]]; arr[[1]] = temp;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with 'smallest' instead of 'largest'
Swapping with 'parent' which is the current node itself
Using an undefined variable
✗ Incorrect
During heapify, we swap the current node with the largest child to maintain the heap property.
3fill in blank
hardFix the error in the heapify function's recursive call to maintain heap property.
DSA Typescript
if (largest !== i) { heapify(arr, arr.length, [1]); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling heapify with 'i' which causes infinite recursion
Calling heapify with 0 which restarts from root unnecessarily
Using arr.length as index which is out of bounds
✗ Incorrect
After swapping, heapify must be called recursively on the index 'largest' to fix the subtree.
4fill in blank
hardFill both blanks to complete the loop that builds the heap from the array.
DSA Typescript
for (let i = [1]; i >= 0; i[2]) { heapify(arr, arr.length, i); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from 0 and incrementing instead of decrementing
Using ++ instead of -- in the loop
Starting from arr.length instead of last non-leaf node
✗ Incorrect
The build heap process starts from the last non-leaf node down to the root, decrementing i each time.
5fill in blank
hardFill all three blanks to complete the heapify function header and left child calculation.
DSA Typescript
function heapify(arr: number[], n: number, [1]: number) { const left = 2 * [2] + [3]; // rest of heapify code }
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 different variable names inconsistently
Confusing left child with right child index
✗ Incorrect
The heapify function uses 'i' as the current index, and left child is at 2*i + 1 in a binary heap.