Implement Min Heap

medium

Implement a min-heap — a priority queue that always keeps the smallest element reachable in O(1) — supporting:

  • insert(x) — add x to the heap.
  • getMin() — return the current minimum (called only when non-empty).
  • extractMin() — remove and return the current minimum (called only when non-empty).
  • size() — return the number of elements.

insert and extractMin should run in O(log n). Store the heap in an array using the standard index arithmetic: the children of i are 2i+1 and 2i+2, the parent is (i-1)/2.

Hints

Store the heap in an array; the minimum lives at index 0.
insert: append at the end and swap upward while smaller than the parent.
extractMin: move the last element to the root, then sift it down past its smaller child.

Common doubts

Full sorting is O(n log n) per change; a heap keeps only enough order to expose the min, so insert and extract are O(log n).
It keeps the tree complete (no gaps), and a single sift-down then restores the heap property.
Swapping the smaller child up guarantees it ends ≤ its new sibling, preserving the min-heap property.

Interview follow-ups

Locate the element (needs an index map), lower its value, and sift it up.
Bottom-up heapify in O(n) instead of O(n log n).

Fun facts

  • A binary heap is how most standard-library priority queues (C++ priority_queue, Python heapq) are implemented.
  • getMin at O(1) with O(log n) updates is exactly the trade-off Dijkstra and Prim rely on.

Asked at

AmazonMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: insert(5), insert(3), insert(8), getMin(), extractMin(), getMin()
Output: null null null 3 3 5
The minimum is 3; after extracting it, the new minimum is 5.
Example 2
Input: insert(2), size(), getMin()
Output: null 1 2
One element: size is 1 and the min is 2.
Constraints

- -10^9 <= x <= 10^9 - At most 2 * 10^4 operations - getMin / extractMin only on a non-empty heap

Solve this problem →