Check if an array represents a min-heap

easy

Given an integer array arr viewed as a complete binary tree (children of index i are 2i+1 and 2i+2), return true if it represents a valid min-heap — every node is ≤ both of its children — and false otherwise. An empty array is a valid heap.

Hints

The min-heap property is local: each parent ≤ its children.
Only indices 0 .. n/2 - 1 have children; leaves can't violate anything.
Scan those internal nodes and compare each to its present children.

Common doubts

Indices n/2 .. n-1 are leaves — they have no children, so there is nothing to check.
No — the property is parent ≤ child, so equal children are fine.
No — the property is local per edge, so checking every parent-child pair once is exactly checking the whole heap.

Interview follow-ups

Flip the comparison: every parent must be ≥ its children.
That's harder — a heap's property is local, but a BST's is a global ordering, so you'd rebuild the tree and inorder-check.

Fun facts

  • Because the property is purely local, this is one of the few tree checks that needs no traversal state at all.
  • The same n/2 boundary shows up in build-heap, which only sifts indices 0 .. n/2 - 1.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: arr = [1, 3, 5, 4, 8]
Output: true
Every parent is ≤ its children.
Example 2
Input: arr = [1, 5, 3, 8, 4]
Output: false
Node 5 (index 1) has child 4 (index 4) which is smaller — violation.
Constraints

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

Solve this problem →