Build Heap from a given array

easy

Given an integer array arr, rearrange it in place into a max-heap (viewing the array as a complete binary tree: children of index i are 2i+1 and 2i+2; a max-heap has every node ≥ its children). Return the resulting array.

Use the bottom-up build: call max-heapify (sift-down) on every internal node, from index n/2 - 1 down to 0. This canonical procedure produces one specific max-heap arrangement.

Hints

Only internal nodes (indices 0 .. n/2-1) need work; leaves are already heaps.
Sift-down each internal node, going from the highest index to the root.
Processing bottom-up guarantees a node's subtrees are already heaps when you sift it.

Common doubts

Sift-down cost is proportional to a node's height; most nodes are near the bottom with tiny height, and the sum of heights over a complete tree is O(n). Insert-and-sift-up pays log n for every element regardless.
Sift-down assumes the child subtrees are already heaps. Bottom-up guarantees that; top-down would sift a node whose children aren't heaps yet.
The bottom-up procedure is deterministic, so it yields one specific arrangement; other valid max-heaps of the same values exist but this build produces this one.

Interview follow-ups

Build a max-heap, then repeatedly swap the root to the end and sift-down the reduced heap — sorting in place.
Sift-down toward the smaller child and stop when the node is ≤ both children.

Fun facts

  • The O(n) build-heap is one of the most surprising results in intro algorithms — linear, despite log-height sifts.
  • Floyd's 1964 'treesort' introduced exactly this bottom-up construction.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: arr = [3, 9, 2, 1, 4, 5]
Output: [9, 4, 5, 1, 3, 2]
Bottom-up sift-down of indices 2, 1, 0 yields a valid max-heap.
Example 2
Input: arr = [5, 4, 3, 2, 1]
Output: [5, 4, 3, 2, 1]
Already a max-heap, so nothing moves.
Constraints

- 0 <= arr.length <= 10^5 - -10^9 <= arr[i] <= 10^9

Solve this problem →