The Wayback Machine - https://web.archive.org/web/20241108102230/https://www.geeksforgeeks.org/how-to-check-if-a-given-array-represents-a-binary-heap/
Open In App

How to check if a given array represents a Binary Heap?

Last Updated : 15 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
30.97%
71K

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>


Output

Yes

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>


Output

Yes

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.



Previous Article
Next Article

Similar Reads

Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array.A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
Check if an array represents Inorder of Binary Search tree or not
Given an array of n elements. The task is to check if it is an Inorder traversal of any Binary Search Tree or not. Examples: Input: arr[] = { 19, 23, 25, 30, 45 }Output: YesExplanation: As the array is sorted in non-decreasing order, it is an Inorder traversal of any Binary Search Tree. Input : arr[] = { 19, 23, 30, 25, 45 }Output : NoExplanation:
4 min read
Check if an encoding represents a unique binary string
Given an encoding of a binary string of length k, the task is to find if the given encoding uniquely identifies a binary string or not. The encoding has counts of contiguous 1s (separated by 0s). For example, encoding of 11111 is {5}, encoding of 01101010 is {2, 1, 1} and encoding of 111011 is {3, 2}. Examples : Input: encoding[] = {3, 3, 3} Length
6 min read
Check if the given graph represents a Bus Topology
Given a graph G, check if it represents a Bus Topology.A Bus Topology is the one shown in the image below: Examples: Input: Output: YES Input: Output: NO A graph of V vertices represents a bus topology if it satisfies the following two conditions: Each node except the starting end ending ones has degree 2 while the starting and ending have degree 1
12 min read
Check if the given graph represents a Star Topology
Given a graph G, the task is to check if it represents a Star Topology.A Star Topology is the one shown in the image below: Examples: Input : Graph = Output : YES Input : Graph = Output : NO A graph of V vertices represents a star topology if it satisfies the following three conditions: One node (also called the central node) has degree V - 1.All n
15+ min read
Check if the given graph represents a Ring Topology
Given a graph G, the task is to check if it represents a Ring Topology.A Ring Topology is the one shown in the image below: Examples: Input : Graph = Output : YES Input : Graph = Output : NO A graph of V vertices represents a Ring topology if it satisfies the following three conditions: Number of vertices >= 3.All vertices should have degree 2.N
11 min read
Check if given path between two nodes of a graph represents a shortest paths
Given an unweighted directed graph and Q queries consisting of sequences of traversal between two nodes of the graph, the task is to find out if the sequences represent one of the shortest paths between the two nodes.Examples: Input: 1 2 3 4 Output: NOExplanation: The first and last node of the input sequence is 1 and 4 respectively. The shortest p
8 min read
Check whether Array represents a Fibonacci Series or not
Given an array arr[] consisting of N integers, the task is to check whether a Fibonacci series can be formed using all the array elements or not. If possible, print "Yes". Otherwise, print "No". Examples: Input: arr[] = { 8, 3, 5, 13 } Output: Yes Explanation: Rearrange given array as {3, 5, 8, 13} and these numbers form Fibonacci series. Input: ar
9 min read
Sorted order printing of a given array that represents a BST
Given an array that stores a complete Binary Search Tree, write a function that efficiently prints the given array in ascending order. For example, given an array [4, 2, 5, 1, 3], the function should print 1, 2, 3, 4, 5 Solution: Inorder traversal of BST prints it in ascending order. The only trick is to modify recursion termination condition in st
4 min read
Minimum steps required to convert X to Y where a binary matrix represents the possible conversions
Given a binary matrix of size NxN where 1 denotes that the number i can be converted to j, and 0 denotes it cannot be converted to. Also given are two numbers X(<N)and Y(<N), the task is to find the minimum number of steps required to convert the number X to Y. If there is no such way possible, print -1. Examples: Input: {{ 0, 0, 0, 0, 0, 0,
13 min read
Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9} 3 / \ 5 9 / \ / \ 6 8 20 10 / \ /12 18 9 Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output: arr[] = {13, 11, 8, 4, 3} Approach: To solve the p
10 min read
Heap Sort for decreasing order using min heap
Given 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. Algorithm : Build a min heap from the input data. At this point, the smallest item is stored
13 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 states that it should be A Complete Binary Tree. For
4 min read
Difference between Min Heap and Max Heap
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. Min-HeapIn a Min-Heap the
3 min read
What's the relationship between "a" heap and "the" heap?
A Heap: "A Heap" refers to the heap data structure where we can store data in a specific order. Heap is a Tree-based data structure where the tree is a complete binary tree. Heap is basically of two types: Max-Heap: The key at the Root node of the tree will be the greatest among all the keys present in that heap and the same property will be follow
15+ min read
Check if a string represents a hexadecimal number or not
Given an alphanumeric string S of length N, the task is to check if the given string represents a hexadecimal number or not. Print Yes if it represents a hexadecimal number. Otherwise, print No. Examples: Input: S = "BF57C" Output: Yes Explanation: Decimal Representation of the given string = 783740 Input: S = "58GK" Output: No Approach: The approa
8 min read
Smallest string without any multiplication sign that represents the product of two given numbers
Given two numbers A and B, the task is to print the string of the smallest possible length which evaluates to the product of the two given numbers i.e., A*B, without using the multiplication sign. Any perfect power of 2 can be expressed in the form of a left-shift operator. For Example: N = 2 = 1<<1 = "<<1" N = 4 = 1<<2 = "<
9 min read
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child, and hence satisfies the min-heap property Input :
6 min read
Check if a given Binary Tree is a Heap
Given 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. all levels except the last should be full).Every node’s value should be greater than or equal to its child node (considering max-heap).Examples: Input: Output: True Input: Output: F
15+ min read
Calculate Stirling numbers which represents the number of ways to arrange r objects around n different circles
S(r, n), represents the number of ways that we can arrange r objects around indistinguishable circles of length n, and every circle n must have at least one object around it. Examples: Input: r = 9, n = 2Output: 109584Input: r = 6, n = 3Output: 225The special cases are: S(r, 0) = 0, trivial.S(r, 1) represents the circular permutation which is equal
15+ min read
Minimum cells traversed to reach corner where every cell represents jumps
Suppose A is at position (0, 0) of a 2-D grid containing 'm' rows and 'n' columns. His aim is to reach the bottom right point of this grid traveling through as minimum number of cells as possible.Each cell of the grid contains a positive integer that defines the number of cells A can jump either in the right or the downward direction when he reache
9 min read
Check if Binary Heap is completely filled
Given an integer N which denotes the number of elements in a binary heap. Check if the binary Heap is completely filled or not. Examples: Input: 7Output: YESExplanation: At height = 0, no. of elements = 1At height = 1, no. of elements = 2At height = 2, no. of elements = 4 Last level is completely filled because at level 2 we need 22 = 4 elements to
4 min read
Array Representation Of Binary Heap
A Binary Heap is a Complete Binary Tree. A binary heap is typically represented as array. The representation is done as: The root element will be at Arr[0]. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]: Arr[(i-1)/2] Returns the parent node Arr[(2*i)+1] Returns the left child node Arr[(2*i)+2] Returns the right child node
1 min read
Complexity analysis of various operations of Binary Min Heap
A Min Heap is a Complete Binary Tree in which the children nodes have a higher value (lesser priority) than the parent nodes, i.e., any path from the root to the leaf nodes, has an ascending order of elements. In the case of a binary tree, the root is considered to be at height 0, its children nodes are considered to be at height 1, and so on. Each
3 min read
Print all the leaf nodes of Binary Heap
Given an array of N elements which denotes the array representation of binary heap, the task is to find the leaf nodes of this binary heap. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 5 6 7 Explanation: 1 / \ 2 3 / \ / \ 4 5 6 7 Leaf nodes of the Binary Heap are: 4 5 6 7 Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output: 6 7 8 9 10
7 min read
Find min and max values among all maximum leaf nodes from all possible Binary Max Heap
Given a positive integer N, the task is to find the largest and smallest elements, from the maximum leaf nodes of every possible binary max-heap formed by taking the first N natural numbers as the nodes' value of the binary max-heap. Examples: Input: N = 2Output: 1 1Explanation: There is only one maximum binary heap with the nodes {1, 2}: In the ab
7 min read
What is Binary Heap
Binary heap is a complete binary tree where the root of any subtree has a higher (or lower based on the type of heap) value than all the nodes in its subtree. Characteristics of Binary Heap: The following are the properties of a binary heap: It is a complete binary tree, which means that all levels of the tree are completely filled, with the except
2 min read
Height of a complete binary tree (or Heap) with N nodes
Consider 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 take a few examples, we can notice that the value of
3 min read
Tournament Tree (Winner Tree) and Binary Heap
Given a team of N players. How many minimum games are required to find the second-best player? We can use adversary arguments based on the tournament tree (Binary Heap). A Tournament tree is a form of min (max) heap which is a complete binary tree. Every external node represents a player and the internal node represents the winner. In a tournament
6 min read
Leaf starting point in a Binary Heap data structure
Binary Heap is a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). In other words, we can say that it's an almost complete binary tree. A Binary heap is typically represented as array. If we take a closer look, we can noticed that in a Heap with number of nodes n, th
2 min read
Article Tags :
three90RightbarBannerImg