The problem
Write a min-heap class stored in a Python list (lessons 1 and 2). push(x) adds a value, pop() removes and returns the smallest value, peek() returns the smallest value without removing it, and len(h) gives the number of values.
h = MinHeap()
h.push(5); h.push(3); h.push(8)
h.peek() # 3
h.pop() # 3
h.pop() # 5
len(h) # 1
Values can repeat. The tests never call pop or peek on an empty heap.
The heapq module is switched off for this problem: write the heap yourself. A heap is a plain list with sift up and sift down (lessons 1 and 2).
One test passes in numbers that count how often they are compared with <, <=, > or >=. They behave like ordinary numbers otherwise. This is how the tests tell an O(log n) heap step from an O(n) scan, which a timer cannot always do.
Limits
- Up to 30,000 values.
pushandpopshould take O(log n) time and comparisons.
Builds on HEAP-1 The heap property and HEAP-2 Sift up and sift down.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Push, then pop | Not run | |
| 2 | peek and len | Not run | |
| 3 | Repeated values | Not run | |
| 4 | Negative values | Not run | |
| 5 | Pushes and pops mixed | Not run | |
| 6 | Heap sort | Not run | |
| 7 | Comparisons | Not run | |
| 8 | 30,000 values | Not run |