Implement Max Heap

medium

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

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

insert and extractMax 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 maximum lives at index 0.
insert: append at the end and swap upward while larger than the parent.
extractMax: move the last element to the root, then sift it down past its larger child.

Common doubts

Only the comparisons flip: sift up while LARGER than the parent, and sift down toward the LARGER child. The structure and complexity are identical.
It keeps the tree complete (no gaps), and a single sift-down then restores the heap property.
Swapping the larger child up guarantees it ends ≥ its new sibling, preserving the max-heap property.

Interview follow-ups

Negate values on insert and negate again on getMax/extractMax, or flip the comparisons.
Bottom-up heapify in O(n) instead of O(n log n).

Fun facts

  • C++'s std::priority_queue is a max-heap by default — exactly this structure.
  • Max-heaps power heap sort's ascending order: repeatedly extract the max to the back.

Asked at

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

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

Solve this problem →