How to check if a given array represents a Binary Heap?
Last Updated :
15 Dec, 2022
Given an array, how to check if the given array represents a Binary Max-Heap.
Examples:
Input: arr[] = {90, 15, 10, 7, 12, 2}
Output: True
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.
Input: arr[] = {9, 15, 10, 7, 12, 11}
Output: False
The given array represents below tree
9
/ \
15 10
/ \ /
7 12 11
The tree doesn't follows max-heap property 9 is
smaller than 15 and 10, and 10 is smaller than 11.
A Simple Solution is to first check root if it's greater than all of its descendants. Then check for children of the root. Time complexity of this solution is O(n2)
An Efficient Solution is to compare root only with its children (not all descendants), if root is greater than its children and the same is true for all nodes, then tree is max-heap (This conclusion is based on transitive property of > operator, i.e., if x > y and y > z, then x > z).
The last internal node is present at index (n-2)/2 assuming that indexing begins with 0.
Below is the implementation of this solution.
C++
// C program to check whether a given array
// represents a max-heap or not
#include <limits.h>
#include <stdio.h>
// Returns true if arr[i..n-1] represents a
// max-heap
bool isHeap(int arr[], int i, int n)
{
// If (2 * i) + 1 >= n, then leaf node, so return true
if (i >= (n - 1) / 2)
return true;
// If an internal node and is
// greater than its children,
// and same is recursively
// true for the children
if (arr[i] >= arr[2 * i + 1] &&
arr[i] >= arr[2 * i + 2]
&& isHeap(arr, 2 * i + 1, n)
&& isHeap(arr, 2 * i + 2, n))
return true;
return false;
}
// Driver program
int main()
{
int arr[] = { 90, 15, 10, 7, 12, 2, 7, 3 };
int n = sizeof(arr) / sizeof(int) - 1;
isHeap(arr, 0, n) ? printf("Yes") : printf("No");
return 0;
}
Java
// Java program to check whether a given array
// represents a max-heap or not
class GFG
{
// Returns true if arr[i..n-1]
// represents a max-heap
static boolean isHeap(int arr[],
int i, int n)
{
// If (2 * i) + 1 >= n, then leaf node, so return true
if (i >= (n - 1) / 2)
{
return true;
}
// If an internal node and
// is greater than its
// children, and same is
// recursively true for the
// children
if (arr[i] >= arr[2 * i + 1]
&& arr[i] >= arr[2 * i + 2]
&& isHeap(arr, 2 * i + 1, n)
&& isHeap(arr, 2 * i + 2, n))
{
return true;
}
return false;
}
// Driver program
public static void main(String[] args)
{
int arr[] = { 90, 15, 10, 7, 12, 2, 7, 3 };
int n = arr.length - 1;
if (isHeap(arr, 0, n)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
// This code contributed by 29AjayKumar
Python3
# Python3 program to check whether a
# given array represents a max-heap or not
# Returns true if arr[i..n-1]
# represents a max-heap
def isHeap(arr, i, n):
# If (2 * i) + 1 >= n, then leaf node, so return true
if i >= int((n - 1) / 2):
return True
# If an internal node and is greater
# than its children, and same is
# recursively true for the children
if(arr[i] >= arr[2 * i + 1] and
arr[i] >= arr[2 * i + 2] and
isHeap(arr, 2 * i + 1, n) and
isHeap(arr, 2 * i + 2, n)):
return True
return False
# Driver Code
if __name__ == '__main__':
arr = [90, 15, 10, 7, 12, 2, 7, 3]
n = len(arr) - 1
if isHeap(arr, 0, n):
print("Yes")
else:
print("No")
# This code is contributed by PranchalK
C#
// C# program to check whether a given
// array represents a max-heap or not
using System;
class GFG
{
// Returns true if arr[i..n-1] represents a
// max-heap
static bool isHeap(int []arr, int i, int n)
{
// If (2 * i) + 1 >= n, then leaf node, so return true
if (i >= (n - 1) / 2)
{
return true;
}
// If an internal node and is greater
// than its children, and same is
// recursively true for the children
if (arr[i] >= arr[2 * i + 1] &&
arr[i] >= arr[2 * i + 2] &&
isHeap(arr, 2 * i + 1, n) &&
isHeap(arr, 2 * i + 2, n))
{
return true;
}
return false;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = {90, 15, 10, 7, 12, 2, 7, 3};
int n = arr.Length-1;
if (isHeap(arr, 0, n))
{
Console.Write("Yes");
}
else
{
Console.Write("No");
}
}
}
PHP
<?php
// PHP program to check whether a given
// array represents a max-heap or not
// Returns true if arr[i..n-1]
// represents a max-heap
function isHeap($arr, $i, $n)
{
// If (2 * i) + 1 >= n, then leaf node, so return true
if ($i >= ($n - 1) / 2)
return true;
// If an internal node and is greater
// than its children, and same is
// recursively true for the children
if ($arr[$i] >= $arr[2 * $i + 1] &&
$arr[$i] >= $arr[2 * $i + 2] &&
isHeap($arr, 2 * $i + 1, $n) &&
isHeap($arr, 2 * $i + 2, $n))
return true;
return false;
}
// Driver Code
$arr = array(90, 15, 10, 7, 12, 2, 7, 3);
$n = sizeof($arr);
if(isHeap($arr, 0, $n))
echo "Yes";
else
echo "No";
// This code is contributed
// by Akanksha Rai
?>
JavaScript
<script>
// Javascript program to check whether a given array
// represents a max-heap or not
// Returns true if arr[i..n-1]
// represents a max-heap
function isHeap(arr,i,n)
{
// If (2 * i) + 1 >= n, then leaf node, so return true
if (i >= (n - 1) / 2)
{
return true;
}
// If an internal node and
// is greater than its
// children, and same is
// recursively true for the
// children
if (arr[i] >= arr[2 * i + 1]
&& arr[i] >= arr[2 * i + 2]
&& isHeap(arr, 2 * i + 1, n)
&& isHeap(arr, 2 * i + 2, n))
{
return true;
}
return false;
}
// Driver program
let arr=[ 90, 15, 10, 7, 12, 2, 7, 3 ];
let n = arr.length - 1;
if (isHeap(arr, 0, n)) {
document.write("Yes<br>");
}
else {
document.write("No<br>");
}
// This code is contributed by rag2127
</script>
Time complexity: O(n)
Auxiliary Space: O(h), Here h is the height of the given tree and the extra space is used due to the recursion call stack.
An Iterative Solution is to traverse all internal nodes and check id the node is greater than its children or not.
C++
// C program to check whether a given array
// represents a max-heap or not
#include <stdio.h>
#include <limits.h>
// Returns true if arr[i..n-1] represents a
// max-heap
bool isHeap(int arr[], int n)
{
// Start from root and go till the last internal
// node
for (int i=0; i<=(n-2)/2; i++)
{
// If left child is greater, return false
if (arr[2*i +1] > arr[i])
return false;
// If right child is greater, return false
if (2*i+2 < n && arr[2*i+2] > arr[i])
return false;
}
return true;
}
// Driver program
int main()
{
int arr[] = {90, 15, 10, 7, 12, 2, 7, 3};
int n = sizeof(arr) / sizeof(int);
isHeap(arr, n)? printf("Yes"): printf("No");
return 0;
}
Java
// Java program to check whether a given array
// represents a max-heap or not
class GFG {
// Returns true if arr[i..n-1] represents a
// max-heap
static boolean isHeap(int arr[], int n) {
// Start from root and go till the last internal
// node
for (int i = 0; i <= (n - 2) / 2; i++) {
// If left child is greater, return false
if (arr[2 * i + 1] > arr[i]) {
return false;
}
// If right child is greater, return false
if (2 * i + 2 < n && arr[2 * i + 2] > arr[i]) {
return false;
}
}
return true;
}
// Driver program
public static void main(String[] args) {
int arr[] = {90, 15, 10, 7, 12, 2, 7, 3};
int n = arr.length;
if (isHeap(arr, n)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to check whether a
# given array represents a max-heap or not
# Returns true if arr[i..n-1]
# represents a max-heap
def isHeap(arr, n):
# Start from root and go till
# the last internal node
for i in range(int((n - 2) / 2) + 1):
# If left child is greater,
# return false
if arr[2 * i + 1] > arr[i]:
return False
# If right child is greater,
# return false
if (2 * i + 2 < n and
arr[2 * i + 2] > arr[i]):
return False
return True
# Driver Code
if __name__ == '__main__':
arr = [90, 15, 10, 7, 12, 2, 7, 3]
n = len(arr)
if isHeap(arr, n):
print("Yes")
else:
print("No")
# This code is contributed by PranchalK
C#
// C# program to check whether a given array
// represents a max-heap or not
using System;
class GFG
{
// Returns true if arr[i..n-1]
// represents a max-heap
static bool isHeap(int []arr, int n)
{
// Start from root and go till
// the last internal node
for (int i = 0; i <= (n - 2) / 2; i++)
{
// If left child is greater,
// return false
if (arr[2 * i + 1] > arr[i])
{
return false;
}
// If right child is greater,
// return false
if (2 * i + 2 < n && arr[2 * i + 2] > arr[i])
{
return false;
}
}
return true;
}
// Driver Code
public static void Main()
{
int []arr = {90, 15, 10, 7, 12, 2, 7, 3};
int n = arr.Length;
if (isHeap(arr, n))
{
Console.Write("Yes");
}
else
{
Console.Write("No");
}
}
}
// This code is contributed
// by 29AjayKumar
PHP
<?php
// PHP program to check whether a
// given array represents a max-heap or not
// Returns true if arr[i..n-1]
// represents a max-heap
function isHeap($arr, $i, $n)
{
// Start from root and go till
// the last internal node
for ($i = 0; $i < (($n - 2) / 2) + 1; $i++)
{
// If left child is greater,
// return false
if($arr[2 * $i + 1] > $arr[$i])
return False;
// If right child is greater,
// return false
if (2 * $i + 2 < $n &&
$arr[2 * $i + 2] > $arr[$i])
return False;
return True;
}
}
// Driver Code
$arr = array(90, 15, 10, 7, 12, 2, 7, 3);
$n = sizeof($arr);
if(isHeap($arr, 0, $n))
echo "Yes";
else
echo "No";
// This code is contributed by Princi Singh
?>
JavaScript
<script>
// Javascript program to check
// whether a given array
// represents a max-heap or not
// Returns true if arr[i..n-1]
// represents a max-heap
function isHeap( arr, n)
{
// Start from root and go till
// the last internal node
for (let i=0; i<=Math.floor((n-2)/2); i++)
{
// If left child is greater,
// return false
if (arr[2*i +1] > arr[i])
return false;
// If right child is greater,
// return false
if (2*i+2 < n && arr[2*i+2] > arr[i])
return false;
}
return true;
}
// driver code
let arr = [90, 15, 10, 7, 12, 2, 7, 3];
let n = arr.length;
if (isHeap(arr, n)) {
document.write("Yes");
}
else {
document.write("No");
}
</script>
Time complexity: O(n), Where n is the total number of elements in the given array.
Auxiliary Space: O(1), As constant extra space is used.
Thanks to Himanshu for suggesting this solution.
Similar Reads
Heap Data Structure A Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value of its children is greater than or equal to its own value. Heaps are usually used to implement priority queues, where the smallest (or largest) element is always at the root of the tree.Basics
2 min read
Introduction to Heap - Data Structure and Algorithm Tutorials A Heap is a special tree-based data structure with the following properties:It is a complete binary tree (all levels are fully filled except possibly the last, which is filled from left to right).It satisfies either the max-heap property (every parent node is greater than or equal to its children) o
15+ min read
Binary Heap A Binary Heap is a complete binary tree that stores data efficiently, allowing quick access to the maximum or minimum element, depending on the type of heap. It can either be a Min Heap or a Max Heap. In a Min Heap, the key at the root must be the smallest among all the keys in the heap, and this pr
13 min read
Advantages and Disadvantages of Heap Advantages of Heap Data StructureTime Efficient: Heaps have an average time complexity of O(log n) for inserting and deleting elements, making them efficient for large datasets. We can convert any array to a heap in O(n) time. The most important thing is, we can get the min or max in O(1) timeSpace
2 min read
Time Complexity of building a heap Consider the following algorithm for building a Heap of an input array A. A quick look over the above implementation suggests that the running time is O(n * lg(n)) since each call to Heapify costs O(lg(n)) and Build-Heap makes O(n) such calls. This upper bound, though correct, is not asymptotically
2 min read
Applications of Heap Data Structure Heap Data Structure is generally taught with Heapsort. Heapsort algorithm has limited uses because Quicksort is better in practice. Nevertheless, the Heap data structure itself is enormously used. Priority Queues: Heaps are commonly used to implement priority queues, where elements with higher prior
2 min read
Comparison between Heap and Tree What is Heap? A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Types of Heap Data Structure: Generally, Heaps can be of two types: Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The sa
3 min read
When building a Heap, is the structure of Heap unique? What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property sta
4 min read
Some other type of Heap
Easy problems on Heap
Check if a given Binary Tree is a HeapGiven a binary tree, check if it has heap property or not, Binary tree needs to fulfil the following two conditions for being a heap: It should be a complete tree (i.e. Every level of the tree, except possibly the last, is completely filled, and all nodes are as far left as possible.).Every nodeâs v
15+ min read
How to check if a given array represents a Binary Heap?Given an array, how to check if the given array represents a Binary Max-Heap.Examples: Input: arr[] = {90, 15, 10, 7, 12, 2} Output: True 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. Input: ar
11 min read
Iterative HeapSortHeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15
11 min read
Find k largest elements in an arrayGiven an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order.Examples:Input: [1, 23, 12, 9, 30, 2, 50], k = 3Output: [50, 30, 23]Input: [11, 5, 12, 9, 44, 17, 2], k = 2Output: [44, 17]Table of Content[Nai
15+ min read
Kâth Smallest Element in Unsorted ArrayGiven an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples:Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content[Naive Ap
15 min read
Height of a complete binary tree (or Heap) with N nodesConsider a Binary Heap of size N. We need to find the height of it. Examples: Input : N = 6 Output : 2 () / \ () () / \ / () () () Input : N = 9 Output : 3 () / \ () () / \ / \ () () () () / \ () ()Recommended PracticeHeight of HeapTry It! Let the size of the heap be N and the height be h. If we tak
3 min read
Heap Sort for decreasing order using min heapGiven an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1}Output : arr[] = {10, 5, 3, 1}Input : arr[] = {1, 50, 100, 25}Output : arr[] = {100, 50, 25, 1}Prerequisite: Heap sort using min heap.Using Min Heap Implementation - O(n Log n) Time
11 min read