Check if an Array Represent Max Heap
Problem Statement:β
Given an arrayΒ arrΒ of sizeΒ n, the task is to check if the given array can be a level order representation of aΒ Max Heap.
-
Example:
Input:
n = 6
arr[] = {90, 15, 10, 7, 12, 2}
Output:
1
Explanation:
The given array represents below tree
90
/ \
15 10
/ \ /
7 12 2
The tree follows max-heap property as every
node is greater than all of its descendants.
// Function to check if the given array represents a Max Heap
bool isMaxHeap(int arr[], int n) {
// Loop through all internal nodes: from 0 to (n-2)/2
for (int i = 0; i <= (n - 2) / 2; i++) {
// Check left child
if (2 * i + 1 < n && arr[i] < arr[2 * i + 1]) {
return false;
}
// Check right child
if (2 * i + 2 < n && arr[i] < arr[2 * i + 2]) {
return false;
}
}
return true;
}
π Required Notes Templateβ
β How It Worksβ
-
Heap Property: In a max heap, for every node
i:arr[i] β₯ arr[left child]arr[i] β₯ arr[right child]
-
Internal Nodes Range:
We only check nodes from index
0to(n β 2) / 2.Why? Nodes after
(nβ2)/2are leaf nodes (no children). -
Step-by-Step:
- Iterate through each internal node.
- If the current node is smaller than any of its children, return
false. - If no violation is found, return
true.
π§© Key Formula / Recurrenceβ
- Internal nodes range:
i β [0, (n β 2) / 2] - For each
i:-
Check:
arr[i] β₯ arr[2 * i + 1](if exists)arr[i] β₯ arr[2 * i + 2](if exists)
-
β±οΈ Time & Space Complexityβ
| Metric | Complexity |
|---|---|
| Time | O(N) |
| Space | O(1) |
- Single pass through all internal nodes.
β οΈ Edge Casesβ
- Empty Array (n = 0) β Should return true (by convention).
- Single Element (n = 1) β Valid max heap.
- Two Elements: Direct parent-child check.
π‘ Other Approachesβ
| Approach | Time | Space |
|---|---|---|
| Bottom-Up Heapify Check | O(N) | O(1) |
| Recursive Tree Validation | O(N) | O(log N) |
β Iterative check (current solution) is simplest for array-based heaps.
π Related Problemsβ
- Validate Min Heap Array
- Build Max Heap from Array
- Convert Array to BST
π¬