Foundation drill for this topic
Easy Heap Operations
In plain English: Show how to add and remove elements from a min-heap, which always gives you the smallest element first.
A heap is a complete binary tree stored in an array where each parent is smaller than its children — push and pop maintain this property in O(log n).
Prompt
Demonstrate pushing and popping elements from a min-heap using Python's heapq module.
Try to write it from scratch before scrolling down.
Solution
import heapq
def heap_demo():
h = []
for val in [5, 3, 8, 1, 2]:
heapq.heappush(h, val) # O(log n) insert
# h is now a valid min-heap
result = []
while h:
result.append(heapq.heappop(h)) # O(log n) extract-min
return result
# Test: heap_demo() == [1, 2, 3, 5, 8]
Quick recall drills to reinforce this pattern.
Stack push/pop is the foundation for all LIFO operations: DFS, undo, and expression parsing.
stack = []
stack.append(x)
stack.pop()
Maintaining a parallel min stack gives O(1) getMin. Classic design problem.
self.stack.append(val)
self.min_stack.append(
min(val, self.min_stack[-1] if self.min_stack else val)
)
heappush maintains the min-heap invariant. Used in merge-k-lists and streaming median.
import heapq
heapq.heappush(h, val)