Practice › Heap & Priority Queue
Check if an Array is a Min-Heap
Easy · Heap & Priority Queue · Asked at Amazon, Microsoft, TCS, Infosys
The array stores a complete binary tree level by level: the children of index i (0-based) are at 2i + 1 and 2i + 2. Print YES if every parent is less than or equal to its children (a min-heap), otherwise NO.
Input
First line: n. Second line: n space-separated integers.
Output
YES or NO.
Constraints
- 1 ≤ n ≤ 10^5
- −10^9 ≤ a[i] ≤ 10^9
Only the parents need checking: indices 0 … n/2 − 1. Compare each with the children that exist.
Example 1
Input
6 1 3 2 7 4 5
Output
YES
Example 2
Input
3 2 1 3
Output
NO
Hints
- Node i has children 2i + 1 and 2i + 2 — when those indices exist.
- Equivalently, every node i > 0 has parent (i − 1) / 2.
Approach
Check every non-root element against its parent: if a[(i − 1) / 2] > a[i] for any i, the heap property fails. Each element is checked once, and the shape is always a complete tree because it is stored in an array, so nothing else needs checking.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> a(n);
for (auto &x : a) cin >> x;
for (int i = 1; i < n; i++)
if (a[(i - 1) / 2] > a[i]) {
cout << "NO\n";
return 0;
}
cout << "YES\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
print("YES" if all(a[(i - 1) // 2] <= a[i] for i in range(1, n)) else "NO")Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
for (int i = 1; i < n; i++)
if (a[(i - 1) / 2] > a[i]) {
System.out.println("NO");
return;
}
System.out.println("YES");
}
}Solve Check if an Array is a Min-Heap online · All practice problems