What you're building
A binary min-heap β a complete binary tree stored in an array where every parent is smaller than its children. The minimum element is always at index 0.
Heaps underpin:
- Priority queues (process schedulers, task runners)
- Dijkstra's shortest-path algorithm
- Median maintenance
- Top-K problems
Requirements
insert(val)β add a value and restore the heap property (bubble up)extractMin()β remove and return the minimum value; restore heap (bubble down)peek()β return the minimum without removing itsize()β return the number of elements
Parent/child index math (0-based array):
- Parent of
i:Math.floor((i - 1) / 2) - Left child of
i:2 * i + 1 - Right child of
i:2 * i + 2
Stretch goals
- Convert to a max-heap by flipping comparisons, or accept a comparator in the constructor
- Implement
heapify(array)to build a heap from an unsorted array in O(n)
What this proves
You understand array-backed trees, index arithmetic, and the invariant maintenance (sift-up / sift-down) that makes heap operations O(log n).
β‘ 50 XP
solution.jsRuns in your browser
Loading editorβ¦
Tests4 to pass
peek returns minimum
extractMin returns values in sorted order
size tracks count
extractMin on empty returns null
Run your code to check these.