3 of 3
Implement a MinHeap class without using Python's heapq module. You need to write the core operations yourself:
bubble_up(i) β After inserting at the end, move the element up until the heap property is restoredbubble_down(i) β After removing the root, move the replacement element down until the heap property is restoredinsert(val) β Add a value to the heapextract_min() β Remove and return the smallest valueheapify(lst) β Turn an arbitrary list into a valid min-heapHeap property: Every parent must be β€ both of its children.
Remember: A heap is stored as a flat list where for index i:
(i - 1) // 22 * i + 12 * i + 2h = MinHeap() h.insert(5) h.insert(3) h.insert(8) h.insert(1) print(h.extract_min()) # Output: 1 print(h.extract_min()) # Output: 3 h2 = MinHeap() h2.heapify([9, 4, 7, 1, 3]) print(h2.extract_min()) # Output: 1 print(h2.extract_min()) # Output: 3
| Operation | Time | Space |
|---|---|---|
insert | O(log n) | O(1) |
extract_min | O(log n) | O(1) |
bubble_up | O(log n) | O(1) |
bubble_down | O(log n) | O(1) |
heapify | O(n) | O(1) |
Why is heapify O(n)? Most nodes are near the bottom and barely move. Only the few nodes near the top bubble down far. The math works out to O(n) total, not O(n log n).
class MinHeap: def __init__(self): self.data = [] def bubble_up(self, i): # Your code here pass def bubble_down(self, i): # Your code here pass def insert(self, val): # Your code here pass def extract_min(self): # Your code here pass def heapify(self, lst): # Your code here pass # Test insert + extract_min: h = MinHeap() for v in [5, 3, 8, 1, 4, 2, 7]: h.insert(v) print(h.extract_min()) # Output: 1 print(h.extract_min()) # Output: 2 print(h.extract_min()) # Output: 3 # Test heapify: h2 = MinHeap() h2.heapify([9, 4, 7, 1, 3]) print(h2.extract_min()) # Output: 1 print(h2.extract_min()) # Output: 3
Implement peek() (return min without removing) and size(), then convert your MinHeap into a MaxHeap by changing the comparison direction in bubble_up and bubble_down.