Check if an array represents a min heap
MediumCheck every parent against its children
Problem
Given an array, return whether it represents a valid min-heap (each parent <= its children).
Check each node at index i is <= its children at 2i+1 and 2i+2.
The idea
The heap property is entirely local: each parent must be at most both children. Checking every internal node — indices 0 to n/2 - 1 — is therefore enough, and takes O(n).
The trick
- Only internal nodes need checking; leaves have no children.
- Guard the child indices against running past the end of the array.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — [10,20,30,21,23] Values: 10, 20, 30, 21, 23.
1for i in 0..n/2-1:2 if a[i]>a[2i+1] or (2i+2<n and a[i]>a[2i+2]): return false3return trueInput
- array
- [10, 20, 30, 21, 23]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- nums = [10, 20, 30, 21, 23]
- Output:
- true
- Explanation:
- Every parent is <= its children.
Example 2
- Input:
- nums = [9, 4, 7]
- Output:
- false
- Explanation:
- 9 > its child 4 → not a min heap.
Example 3
- Input:
- nums = [1, 2, 3, 4]
- Output:
- true
- Explanation:
- Parents stay smallest.
Practice this problem:GeeksforGeeks · max-heap variant(opens in a new tab)
Finished the walkthrough? Add it to your streak.