KatInterview

Build a Min-Heap Data Structure from Scratch

Data Structure DesignAuto-graded · 17 test cases
MediumAuto-gradedData Structure Designheaps-sortingarraysdata-structures

Last updated

Evaluates ability to implement a complete binary min-heap using array indexing, bubble-up, and bubble-down operations without library support.

Build a min-heap data structure without using any standard library heap implementations (like Python's heapq, Java's PriorityQueue, or C++'s std::priority_queue).

Your heap should store integers, allow duplicate values, and support the fundamental heap operations efficiently.

Implement the MinHeap class with these methods:

  • push(value: int) -> None: Add an integer into the heap.
  • peek() -> int | None: Return the smallest element without removing it. Return None if the heap is empty.
  • pop() -> int | None: Remove and return the smallest element. Return None if the heap is empty.
  • size() -> int: Return how many elements are currently stored.

Your implementation will be tested by calling a single function that replays a sequence of operations and collects the results.

Constraints

  • Up to 2 × 10^5 total operations across all methods
  • Integer values: -10^9 ≤ value ≤ 10^9
  • push must execute in O(log n) time
  • pop must execute in O(log n) time
  • peek must execute in O(1) time
  • size must execute in O(1) time
  • Use an array-based representation of a complete binary tree

Examples

Example 1

Input: min_priority_queue(['push', 'push', 'push', 'push', 'peek', 'size', 'pop', 'pop', 'pop', 'size', 'pop', 'pop', 'peek'], [[5], [3], [8], [3], [], [], [], [], [], [], [], [], []])

Output: [None, None, None, None, 3, 4, 3, 3, 5, 1, 8, None, None]

Example 2

Input: min_priority_queue(['peek', 'pop', 'size', 'push', 'push', 'peek', 'pop', 'pop', 'pop', 'pop', 'size'], [[], [], [], [-2], [7], [], [], [], [], [], []])

Output: [None, None, 0, None, None, -2, -2, 7, None, None, 0]

Hints

Hint 1

Store the heap in a list where for any element at index i, its parent is at (i-1)//2 and its children are at 2*i+1 and 2*i+2

Hint 2

After inserting at the end, restore the heap property by bubbling the new element upward while it's smaller than its parent

Hint 3

When removing the minimum, replace the root with the last element, then bubble it downward by swapping with the smaller of its two children