Convert Min Heap to Max Heap

medium

Given an integer array arr that currently represents a min-heap (every node ≤ its children), rearrange it in place into a max-heap (every node ≥ its children) and return it. The array is viewed as a complete binary tree: children of index i are 2i+1 and 2i+2.

Hints

Don't try to reuse the min-heap order — it doesn't map to a max-heap.
This is just build-max-heap from the array.
Max-heapify every internal node from n/2 - 1 down to 0.

Common doubts

No. Reversal produces a valid max-heap only by coincidence; in general it violates the property, e.g. reversing [1,5,6,8,9,7].
No — the largest element could be anywhere and must reach the root, so you rebuild in O(n), the same as build-heap.
Bottom-up heapify is O(n); repeated inserts are O(n log n) and produce a different (still valid) arrangement.

Interview follow-ups

Symmetrically — build-min-heap by sifting toward the smaller child.
The bottom-up build is deterministic and yields one specific arrangement; other valid max-heaps of the same values exist.

Fun facts

  • This problem exists mainly to break the 'reverse it' intuition — the answer is the humble build-heap.
  • It's the same O(n) construction that powers heap sort's first phase.

Asked at

AmazonMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: arr = [1, 3, 6, 5, 9, 8]
Output: [9, 5, 8, 1, 3, 6]
Rebuilt bottom-up into a valid max-heap.
Example 2
Input: arr = [1, 2, 3, 4, 5, 6]
Output: [6, 5, 3, 4, 2, 1]
Build-max-heap; note this is not simply the reversed array.
Constraints

- 0 <= arr.length <= 10^5 - -10^9 <= arr[i] <= 10^9 - arr is a valid min-heap

Solve this problem →