486. Add Values and Fetch Smallest from Min Heap
Add Values and Fetch Smallest from Min Heap

Write pseudocode for a binary min-heap that lets you add integer values and fetch the smallest value. Here, fetching removes the value from the heap.

Method Signatures

MinHeap()
  • Create an empty heap.
void add(int value)
  • Insert value into the heap.
  • Duplicate values are stored separately.
int fetchFirst()
  • Remove and return one occurrence of the smallest value.
  • This method is called only when the heap is not empty.

Requirements

  • Use a List<Integer> to store the binary heap. Each parent's value must be no greater than its children's values.
  • Implement the heap operations yourself without built-in heap or priority queue functions.
  • Use O(log n) amortized time per operation and O(n) space, where n is the heap size.

Constraints

  • -1,000,000,000 ≤ value ≤ 1,000,000,000
  • At most 100,000 total calls to add and fetchFirst.

Examples

Calls run in order on the same heap within each example.

Example 1

  1. MinHeap() creates an empty heap.
  2. add(value = 14) returns no value.
  3. add(value = 6) returns no value.
  4. add(value = 10) returns no value.
  5. fetchFirst() returns 6.
  6. add(value = 3) returns no value.
  7. fetchFirst() returns 3.
  8. fetchFirst() returns 10.
  9. fetchFirst() returns 14.

Example 2

  1. MinHeap() creates an empty heap.
  2. add(value = -5) returns no value.
  3. add(value = -5) returns no value.
  4. add(value = 0) returns no value.
  5. fetchFirst() returns -5.
  6. fetchFirst() returns -5.
  7. fetchFirst() returns 0.

Both copies of -5 are removed before 0.



Please use Laptop/Desktop or any other large screen to add/edit code.