Check if an array represents a min heap
Pattern: Heap implementation
An array is a min heap when every child is at least its parent. Child i has parent (i - 1) / 2, so one pass over i = 1 .. n - 1 checks every pair. The array is always a complete tree, so nothing else is needed.
The problem
Return whether the array is a min heap: every value is at most the values of its children at 2i + 1 and 2i + 2.
[10, 20, 30, 21, 23] is true; [10, 20, 30, 25, 15] is false. Equal values are allowed.
Think first
- What exactly must hold between a parent and a child?
- Is it easier to loop over parents or over children?
- Do you need to check that the tree is complete?
Hints
Brute force, and why it fails
Check each parent against both children, with bounds checks on each: the same O(n), more code.
The key insight
Every parent-child pair is one child index and its parent, so one loop over children covers all of them.
Dry run
nums = [10, 20, 30, 21, 23]. Index 1 (20) and 2 (30) are at least their parent 10.
The plan
for i from 1 to n - 1:
if nums[(i - 1) / 2] > nums[i]: return false
return true
Complexity
- Time
O(n)- Space
O(1)
One comparison per child.
Edge cases
- One value: true.
- Equal parent and child: still true.
- Only the last child is wrong.
I've built my logic, show the code
Java
class Solution {
public boolean isHeap(int[] nums) {
for (int i = 1; i < nums.length; i++) {
if (nums[(i - 1) / 2] > nums[i]) return false; // a child smaller than its parent
}
return true;
}
}C++
class Solution {
public:
bool isHeap(vector<int>& nums) {
for (size_t i = 1; i < nums.size(); i++) {
if (nums[(i - 1) / 2] > nums[i]) return false; // a child smaller than its parent
}
return true;
}
};Python
class Solution:
def isHeap(self, nums: list[int]) -> bool:
return all(nums[(i - 1) // 2] <= nums[i] for i in range(1, len(nums))) # no child below its parentCommon mistakes
- Checking only neighbours
nums[i] <= nums[i + 1], which is sortedness, not heap order. - Using
<and rejecting equal values.