Problem 447861 · easy · Phase 04 Non-Linear Data Structures

Build a Min-Heap From Scratch

heaps · classes · sift up · sift down

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 integer x.
  • pop() removes and returns the smallest value, or None if the heap is empty.
  • peek() returns the smallest value without removing it, or None if 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**5 operations in total, values in [-10**9, 10**9]
  • Target complexity: push and pop in O(log n); peek and size in 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
Starting Python…