Complete the code to get the index of the left child in a heap.
def left_child(index): return 2 * index [1] 1
The left child of a node at index index in a heap is at 2 * index + 1.
Complete the code to swap two elements in a list.
def swap(heap, i, j): heap[i], heap[j] = heap[[1]], heap[i]
To swap elements at positions i and j, assign heap[i] to heap[j] and vice versa.
Fix the error in the bubble down condition to check if the right child exists.
if right < len(heap) and heap[right] [1] heap[smallest]: smallest = right
To maintain a min-heap, if the right child is smaller than the current smallest, update smallest to right.
Fill both blanks to complete the bubble down loop condition and swap.
while [1] < len(heap): swap(heap, index, [2]) index = [2]
The loop continues while the smallest child index is valid. We swap with the smallest child and update the index to it.
Fill all three blanks to complete the extract min function with bubble down.
def extract_min(heap): if not heap: return None min_val = heap[0] heap[0] = heap.pop() index = 0 while True: left = 2 * index + 1 right = 2 * index + 2 smallest = [1] if left < len(heap) and heap[left] < heap[smallest]: smallest = left if right < len(heap) and heap[right] < heap[smallest]: smallest = right if smallest == index: break swap(heap, index, [2]) index = [3] return min_val
Start with smallest = index. Update it to left or right child if smaller. Swap with smallest and update index to smallest.
