Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the parent index in a heap.
DSA Javascript
const parentIndex = Math.floor((index [1] 1) / 2);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' causes wrong parent calculation.
Using '*' or '/' without subtracting 1 leads to incorrect index.
✗ Incorrect
In a binary heap, the parent index is calculated by subtracting 1 from the current index, then dividing by 2 and taking the floor.
2fill in blank
mediumComplete the condition to check if bubble up should continue.
DSA Javascript
while (index > 0 && heap[index] [1] heap[parentIndex]) {
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' reverses the heap property check.
Using '===' causes infinite loop or no swaps.
✗ Incorrect
Bubble up continues while the current node is greater than its parent in a max heap.
3fill in blank
hardFix the error in swapping heap elements during bubble up.
DSA Javascript
const temp = heap[index];
heap[index] = heap[parentIndex];
heap[parentIndex] = [1]; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning heap[index] or heap[parentIndex] again causes incorrect swap.
Using index instead of temp loses the original value.
✗ Incorrect
We store the original value in temp and assign it back to the parent's position to complete the swap.
4fill in blank
hardFill both blanks to update index and parentIndex after swapping.
DSA Javascript
index = [1]; parentIndex = Math.floor(([2] - 1) / 2);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using index instead of parentIndex causes infinite loop.
Incorrect recalculation of parentIndex breaks heap property.
✗ Incorrect
After swapping, index moves up to parentIndex, and parentIndex recalculates based on the new index.
5fill in blank
hardFill all three blanks to complete the bubble up function for heap insert.
DSA Javascript
function bubbleUp(heap) {
let index = heap.length - 1;
let parentIndex = Math.floor((index [1] 1) / 2);
while (index > 0 && heap[index] [2] heap[parentIndex]) {
const temp = heap[index];
heap[index] = heap[parentIndex];
heap[parentIndex] = [3];
index = parentIndex;
parentIndex = Math.floor((index - 1) / 2);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' in parent index calculation.
Using '<' instead of '>' in comparison.
Not using temp for swapping causes value loss.
✗ Incorrect
The bubble up function uses index - 1 to find parent, compares if child is greater than parent, and swaps using temp.