The problem
Rearrange a list, in place, so that it becomes a min-heap: every a[i] is at least its parent a[(i - 1) // 2]. Change the list you are given and return nothing, as heapq.heapify does.
a = [5, 3, 8, 1, 9, 2]
heapify(a)
# a is now a min-heap, for example [1, 3, 2, 5, 9, 8]
Any arrangement that obeys the heap rule passes. The tests check the rule, not one exact list.
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); you can copy your class from HEAP-P1.
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 200,000 values. Use at most 3n comparisons: pushing the values one at a time is not fast enough.
Builds on HEAP-3 Building a heap in O(n).
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 | Small list | Not run | |
| 2 | Empty and one | Not run | |
| 3 | Already a heap | Not run | |
| 4 | Decreasing | Not run | |
| 5 | Repeated values | Not run | |
| 6 | Kept in place | Not run | |
| 7 | Comparisons, decreasing | Not run | |
| 8 | Comparisons, mixed | Not run | |
| 9 | 200,000 values | Not run |