Heapify Algorithm

easy

Given an integer array arr (viewed as a complete binary tree in array form: the children of index i are 2i+1 and 2i+2) and an index i, perform max-heapify at i — sink the element at i down to its correct place so the subtree rooted at i satisfies the max-heap property (each node ≥ its children). Return the resulting array.

To sink it: compare arr[i] with its two children; if the larger child exceeds it, swap them and continue from the child's position. If i is out of range, return the array unchanged.

Hints

Think of the array as a complete binary tree: children of i are 2i+1 and 2i+2.
Compare arr[i] with the LARGER of its two children.
If the larger child exceeds arr[i], swap and repeat from the child's position.

Common doubts

After the swap the promoted child becomes the new parent; if you promoted the smaller child, the larger one could still exceed it and violate the property.
Each swap moves down exactly one level, and a complete binary tree has height log n, so at most log n swaps happen along one path.
Heapify only guarantees a valid heap when the child subtrees are already heaps; that's why build-heap calls it bottom-up.

Interview follow-ups

Call heapify on every index from n/2 - 1 down to 0 — bottom-up build in O(n).
Identical, but swap with the smaller child and stop when the node is ≤ both children.

Fun facts

  • Heapify is the one primitive behind extract-min, build-heap, and heap sort — learn it once, reuse everywhere.
  • CLRS calls this MAX-HEAPIFY; it's the heart of the O(n) build-heap analysis.

Asked at

AmazonMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: arr = [1, 10, 5, 8, 3], i = 0
Output: [10, 8, 5, 1, 3]
1 sinks past 10 then past 8 to reach a leaf.
Example 2
Input: arr = [9, 7, 8, 1, 2], i = 0
Output: [9, 7, 8, 1, 2]
9 is already ≥ both children, so nothing moves.
Constraints

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

Solve this problem →