Opening the reading…
Opening the reading…
HEAP (PRIORITY QUEUE) › INTRODUCTORY QUESTIONS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The array already describes the tree structure through its indices, so you do not need to build any nodes or links. A max heap is valid exactly when every child is no larger than its parent. For a child at index i greater than 0, integer division gives its parent at index (i - 1) / 2. That lets you verify each relationship directly from the array.
Start at index 1 because index 0 is the root and has no parent. For each later element, compute its parent and compare the two values. The moment a child is larger than its parent, the max-heap condition is false; if every child passes, every parent-child relationship is valid. Each child is inspected once, so the check stays linear and uses no tree storage.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The loop performs one constant-time parent calculation and one comparison for each of the n - 1 non-root elements. No child or parent relationship is revisited, so the total work is linear. |
| Space | O(1) extra | Only the index and parent variables are stored; the input array is not copied, and the required boolean result is not counted as working memory. This bound does not degrade with the shape of the complete tree because the algorithm never creates a recursion stack or auxiliary structure. |
#include <vector>
using namespace std;
class Solution {
public:
bool isMaxHeap(vector<int>& arr) {
for (int i = 1; i < static_cast<int>(arr.size()); ++i) {
int parent = (i - 1) / 2;
if (arr[parent] < arr[i]) {
return false;
}
}
return true;
}
};The loop starts at 1 rather than 0 because the parent formula only applies to a non-root node. The comparison uses arr[parent] < arr[i], not a strict greater-than requirement: equal parent and child values are allowed in a max heap. Returning as soon as a violation appears also avoids doing work after the answer is already known.
You can reverse the direction: visit each possible parent and inspect its left and right children when those indices exist. This is equally valid and has the same O(n) time and O(1) extra space. The child-to-parent loop is usually shorter because every non-root position has exactly one parent, while a parent loop needs two boundary checks.
#include <vector>
using namespace std;
class Solution {
public:
bool isMaxHeap(vector<int>& arr) {
int n = static_cast<int>(arr.size());
for (int parent = 0; parent < n / 2; ++parent) {
int left = 2 * parent + 1;
int right = left + 1;
if (arr[parent] < arr[left]) {
return false;
}
if (right < n && arr[parent] < arr[right]) {
return false;
}
}
return true;
}
};