Build a Min-Heap Data Structure from Scratch
Data Structure DesignAuto-graded · 17 test casesLast 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. ReturnNoneif the heap is empty.pop() -> int | None: Remove and return the smallest element. ReturnNoneif 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^5total operations across all methods - Integer values:
-10^9 ≤ value ≤ 10^9 pushmust execute inO(log n)timepopmust execute inO(log n)timepeekmust execute inO(1)timesizemust execute inO(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
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Implement a binary min-heap using a flat list where elements are organized in complete-binary-tree order. Each node satisfies the min-heap property: every parent is less than or equal to its children.
For an element at position i:
- Its parent sits at index
(i - 1) // 2 - Its left child sits at index
2 * i + 1 - Its right child sits at index
2 * i + 2
The minimum element always lives at the root (index 0), making peek a constant-time array lookup.
Push: Append the new value to the end of the list, preserving the complete tree shape. Then bubble it upward: repeatedly swap with the parent while the value is smaller than its parent. This walk follows one leaf-to-root path.
Pop: Save the root value. Replace the root with the last element and remove the last position. Then bubble the new root downward: at each step, compare it with both children and swap with the smaller child if that child is smaller than the current node. Continue until the node is smaller than both children or reaches a leaf. This restores the heap property along one root-to-leaf path.
Peek: Return the element at index 0, or None if empty.
Size: Return the length of the list.
Why It Works
The heap property states that each parent is at most as large as its children. Before insertion, this property holds everywhere. Appending a value can only violate the property between the new leaf and its ancestors. Bubbling up fixes violations one level at a time: if the current node is smaller than its parent, swapping them fixes that edge, but the swapped parent may now violate the property with its parent. The process stops when the node is no longer smaller than its parent, which means all parent-child pairs are correct.
When extracting, both subtrees of the root are still valid heaps. Only the new root (formerly the last element) might be too large. Swapping it with its smaller child fixes the local violation: the smaller child becomes the parent of the larger child, maintaining order. The displaced node may now be too large for its new position, so the process repeats. Choosing the smaller child is critical; swapping with the larger child would place the larger child above the smaller one, breaking the heap property.
Duplicates are handled naturally. Bubble-up stops when the parent is less than or equal, and bubble-down only swaps on strict inequality. Equal values remain stable, and the heap property allows ties.
Complexity
- push: O(log n) — one leaf-to-root path through a tree of height ⌊log₂ n⌋
- pop: O(log n) — one root-to-leaf path
- peek: O(1) — direct array access
- size: O(1) — list length lookup
Space usage is O(n) for storing the elements. Both bubble operations use iteration instead of recursion, keeping auxiliary space at O(1).
With up to 200,000 operations, the heap height stays around 18 levels, making all operations fast in practice.
Edge Cases
- Empty heap:
peekandpopreturnNonerather than raising exceptions. - Single element: When extracting from a heap with one element, return and remove that element directly. The general path would fail because after popping the last element, writing to index 0 would access an empty list.
- Duplicates: Handled transparently by the inequality checks in bubble operations.
- Negative values: Python handles arbitrary integers without overflow; only comparisons are performed.
- Missing right child: Internal nodes near the bottom may have only a left child. Check both child indices against the heap size separately.
Solution Code
from typing import List, Optional
class MinHeap:
def __init__(self):
self.heap = []
def push(self, value: int) -> None:
self.heap.append(value)
self._bubble_up(len(self.heap) - 1)
def peek(self) -> Optional[int]:
return self.heap[0] if self.heap else None
def pop(self) -> Optional[int]:
if not self.heap:
return None
if len(self.heap) == 1:
return self.heap.pop()
min_value = self.heap[0]
self.heap[0] = self.heap.pop()
self._bubble_down(0)
return min_value
def size(self) -> int:
return len(self.heap)
def _bubble_up(self, index: int) -> None:
while index > 0:
parent_idx = (index - 1) // 2
if self.heap[parent_idx] <= self.heap[index]:
break
self.heap[parent_idx], self.heap[index] = self.heap[index], self.heap[parent_idx]
index = parent_idx
def _bubble_down(self, index: int) -> None:
n = len(self.heap)
while True:
left_child = 2 * index + 1
right_child = 2 * index + 2
smallest = index
if left_child < n and self.heap[left_child] < self.heap[smallest]:
smallest = left_child
if right_child < n and self.heap[right_child] < self.heap[smallest]:
smallest = right_child
if smallest == index:
break
self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index]
index = smallest
def min_priority_queue(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
heap = MinHeap()
results = []
for op, args in zip(operations, arguments):
if op == "push":
heap.push(args[0])
results.append(None)
elif op == "peek":
results.append(heap.peek())
elif op == "pop":
results.append(heap.pop())
elif op == "size":
results.append(heap.size())
return results