A Min Heap always keeps the smallest element at the root, making it ideal for quickly accessing or removing the smallest item in a changing dataset.
A Max Heap keeps the largest element at the root, so it is best when you want quick access to the largest item in a dataset.
import heapq heap = [] heapq.heappush(heap, 5) heapq.heappush(heap, 3) heapq.heappush(heap, 8) heapq.heappush(heap, 1) print(heap)
Python's heapq module implements a Min Heap. After inserting 5, 3, 8, and 1, the smallest element 1 is at the root (index 0), and the heap property is maintained.
import heapq heap = [] heapq.heappush(heap, -2) heapq.heappush(heap, -7) heapq.heappush(heap, -4) print([-x for x in heap])
By pushing negative values, the smallest negative corresponds to the largest positive. The heap list stores [-7, -2, -4], so negating gives [7, 4, 2].
Using a Max Heap for the smaller half and a Min Heap for the larger half allows quick access to the middle values needed to find the median efficiently.
