A min-heap that always hands back the smallest
When work arrives out of order but must be processed smallest-first — earliest deadline, closest timestamp, cheapest route — a heap beats re-sorting an array on every insert.
Implement a MinHeap class holding numbers. It is constructed with no arguments and starts empty. push(value) inserts a number and returns the new size. pop() removes and returns the smallest number currently held, or returns undefined when the heap is empty. peek() returns the smallest number without removing it, or undefined when empty. size() returns how many numbers are held.
Only the sequence of values coming out of pop() is specified; the internal arrangement is yours to choose. Duplicate values are allowed and each must come out separately.
What it has to do
- Repeated
pop()calls return the values in ascending order. - Duplicate values are each returned separately.
peek()returns the smallest value without removing it.pop()andpeek()returnundefinedon an empty heap.- Pushing and popping can be interleaved in any order.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.