Implement a binary min-heap yourself, without using heapq. Keep the values in a plain Python list where the children of the item at index i sit at indices 2*i + 1 and 2*i + 2, and every parent is less than or equal to its children.
Write a class MinHeap with:
MinHeap()creates an empty heap.push(x)inserts the integerx.pop()removes and returns the smallest value, orNoneif the heap is empty.peek()returns the smallest value without removing it, orNoneif the heap is empty.size()returns how many values are stored.
Duplicates are allowed and are returned as many times as they were pushed.
Examples
Input: ops = ["MinHeap", "push", "push", "push", "peek", "pop", "pop", "size", "pop", "pop"]
args = [[], [5], [3], [8], [], [], [], [], [], []]
Output: [None, None, None, None, 3, 3, 5, 1, 8, None]
Explanation: after pushing 5, 3, 8 the smallest is 3. Popping yields 3 then 5, one value
(8) remains, popping it leaves the heap empty, and the last pop returns None.
Constraints
- Up to
10**5operations in total, values in[-10**9, 10**9] - Target complexity:
pushandpopin O(log n);peekandsizein O(1).
Goals
- Store a complete binary tree in a flat list using index arithmetic
- Restore the heap property after an insert with sift-up
- Restore the heap property after removing the root with sift-down