Complete the code to get the index of the left child in a heap array.
function leftChildIndex(parentIndex: number): number {
return 2 * parentIndex [1] 1;
}In a heap stored as an array, the left child of a node at index i is at 2 * i + 1.
Complete the code to swap two elements in the heap array.
function swap(heap: number[], i: number, j: number): void {
const temp = heap[i];
heap[i] = heap[[1]];
heap[j] = temp;
}To swap elements at indices i and j, assign heap[i] to heap[j].
Fix the error in the bubbleDown function to correctly update the index after swapping.
function bubbleDown(heap: number[], index: number): void {
const length = heap.length;
let smallest = index;
const left = 2 * index + 1;
const right = 2 * index + 2;
if (left < length && heap[left] < heap[smallest]) {
smallest = left;
}
if (right < length && heap[right] < heap[smallest]) {
smallest = right;
}
if (smallest !== index) {
swap(heap, index, smallest);
index = [1];
bubbleDown(heap, index);
}
}After swapping, the new index to continue bubbling down is the smallest child index.
Fill both blanks to complete the extractMin function that removes the smallest element and restores the heap.
function extractMin(heap: number[]): number | null {
if (heap.length === 0) return null;
const min = heap[0];
heap[0] = heap[[1]];
heap.pop();
bubbleDown(heap, [2]);
return min;
}Replace the root with the last element at index heap.length - 1, then bubble down from index 0.
Fill all three blanks to complete the bubbleDown function for a max heap.
function bubbleDownMax(heap: number[], index: number): void {
const length = heap.length;
let largest = index;
const left = 2 * index + 1;
const right = 2 * index + 2;
if (left < length && heap[left] [1] heap[largest]) {
largest = left;
}
if (right < length && heap[right] [2] heap[largest]) {
largest = right;
}
if (largest !== index) {
swap(heap, index, largest);
index = [3];
bubbleDownMax(heap, index);
}
}For a max heap, compare if children are greater than current largest, then update largest and continue bubbling down from largest.