Complete the code to import the correct heap module for min heap operations.
import [1]
The heapq module provides heap queue algorithms, which are used to implement min heaps in Python.
Complete the code to push a number into the max heap (using min heap with negated values).
import heapq max_heap = [] num = 10 heapq.[1](max_heap, -num)
The heappush function adds an element to the heap while maintaining the heap property.
Fix the error in the code to balance the two heaps after insertion.
if len(max_heap) > len(min_heap) + [1]: val = -heapq.heappop(max_heap) heapq.heappush(min_heap, val)
We balance heaps when the size difference is more than 1, so the correct number is 1.
Fill both blanks to correctly calculate the median when heaps have equal size.
if len(max_heap) == len(min_heap): median = (-max_heap[[1]] + min_heap[[2]]) / 2
The root of both heaps is at index 0. For max_heap (simulated min heap with negation), -max_heap[0] gives the maximum value of the left half; min_heap[0] gives the minimum value of the right half.
Fill all three blanks to insert a number and rebalance heaps correctly.
def add_num(num): if not max_heap or num <= -max_heap[0]: heapq.[1](max_heap, -num) else: heapq.[2](min_heap, num) if len(max_heap) > len(min_heap) + [3]: val = -heapq.heappop(max_heap) heapq.heappush(min_heap, val)
We use heappush to add elements to heaps and rebalance when size difference is more than 1.
