Skip to content
Onsite

Implement Min Heap

MediumP1Coding

JavaScript has no built-in heap, so interviews often ask you to write one. Implement a binary min-heap of integers.

Implement the MinHeap class:

  • MinHeap() creates an empty heap.
  • push(val) inserts val.
  • pop() removes and returns the smallest value, or -1 if the heap is empty.
  • peek() returns the smallest value without removing it, or -1 if the heap is empty.
  • size() returns the number of values stored.

All stored values are non-negative, so -1 is never a real value. push and pop must run in O(log n); peek and size in O(1). Duplicates are allowed.

Example 1

Input
["MinHeap","push","push","push","peek","pop","pop","size"] [[],[5],[3],[8],[],[],[],[]]
Output
[null,null,null,null,3,3,5,1]

Constraints

  • 0 <= val <= 10^9
  • At most 10^5 calls in total.

Hints

Run checks the 2 visible tests, Submit all 7.