VOOZH about

URL: https://www.geeksforgeeks.org/dsa/how-to-check-if-a-given-array-represents-a-binary-heap/

⇱ Check if an Array is Max Heap - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if an Array is Max Heap

Last Updated : 30 Apr, 2026

Given an array arr[], determine whether it represents a valid binary max heap. Return true if it does; otherwise, return false.

Examples:

Input: arr[] = [90, 15, 10, 7, 12, 2]
Output: true
Explanation: The tree follows max-heap property as every node is greater than all of its descendants.

šŸ‘ aa


Input: arr[] = [9, 15, 10, 7, 12, 11]
Output: false
Explanation: The tree doesn't follows max-heap property 9 is smaller than 15 and 10, and 10 is smaller than 11.

šŸ‘ bb

[Naive Approach] Recursive Approach - O(n) Time and O(Log n) Space

  • We compare compare each node with its immediate children, not all descendants.
  • If every node is greater than or equal to its children, then by the transitive property (if x > y and y > z, then x > z), the whole tree satisfies the max-heap property.
  • The children of index i are at 2 i + 1 and 2 i + 2. A node will have children only if 2 i + 1 < n, which gives i ≤ (n āˆ’ 2)/2. So, we traverse only up to index (n āˆ’ 2)/2 because nodes after that are leaf nodes and do not have children, preventing out-of-bounds.

Algorithm:

  • Start from root and recursively check each node: it must be ≄ its left child (2i+1) and right child (2i+2).
  • Stop when reaching leaf nodes (i > (n-2)/2); if all checks pass, the array represents a max-heap.

Output
true

[Expected Approach] Iterative - O(n) Time and O(1) Space.

This is mainly an iterative version of the above recursive implementation. We traverse from 0 to index i ≤ (n āˆ’ 2 ) / 2 because nodes beyond this point are leaf nodes and do not have any children. Indexes of children nodes of index i are 2 āˆ— i + 1 and 2 āˆ— i + 2

Algorithm:

  • Traverse all internal nodes (i = 0 to (nāˆ’2)/2) and check if each parent is ≄ its left (2 * i + 1) and right child (2 * i+ 2).
  • If any child is greater than its parent return false; otherwise, after full traversal, return true (valid max-heap).

Output
true
Comment
Article Tags: