Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get the parent index of a node in a heap.
DSA Typescript
const parentIndex = (index: number) => 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 / instead of - leads to incorrect index.
✗ Incorrect
To find the parent index in a heap, subtract 1 from the current index before dividing by 2.
2fill in blank
mediumComplete the code to swap two elements in the heap array.
DSA Typescript
const swap = (arr: number[], i: number, j: number) => { 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 arr[i] with arr[i] does nothing.
Using 0 or arr.length as index causes errors.
✗ Incorrect
To swap elements, assign arr[i] to arr[j] and arr[j] to temp.
3fill in blank
hardFix the error in the bubble up loop condition to continue while the current node is smaller than its parent.
DSA Typescript
let parent = Math.floor((index - 1) / 2); while (index > 0 && heap[index] [1] heap[parent]) { swap(heap, index, parent); index = parent; parent = Math.floor((index - 1) / 2); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' reverses the heap property.
Using '==' or '!=' causes infinite or no swaps.
✗ Incorrect
In a min-heap, bubble up continues while current node is less than its parent.
4fill in blank
hardFill both blanks to complete the bubble up function that inserts a value and restores heap order.
DSA Typescript
function bubbleUp(heap: number[], value: number) {
heap.push(value);
let index = heap.length [1] 1;
while (index > 0) {
const parent = Math.floor((index [2] 1) / 2);
if (heap[index] >= heap[parent]) break;
swap(heap, index, parent);
index = parent;
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of - causes wrong indices.
Using * or / breaks the parent calculation.
✗ Incorrect
Index starts at last element (length - 1). Parent index uses (index - 1) / 2.
5fill in blank
hardFill all three blanks to complete the bubble up logic with correct conditions and swapping.
DSA Typescript
function bubbleUp(heap: number[], value: number) {
heap.push(value);
let index = heap.length [1] 1;
while (index > 0) {
const parent = Math.floor((index [2] 1) / 2);
if (heap[index] [3] heap[parent]) break;
swap(heap, index, parent);
index = parent;
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of - for indices.
Using '<' or '!=' in break condition causes wrong loop behavior.
✗ Incorrect
Index starts at length - 1; parent uses (index - 1)/2; break if current node >= parent.