Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check heap is forming max heap or not in Python
Suppose we have a list representing a heap tree. As we know, a heap is a complete binary tree. We have to check whether the elements are forming a max heap or not. In a max heap, every parent element is larger than both of its children.
So, if the input is like nums = [8, 6, 4, 2, 0, 3], then the output will be True because all parent elements are larger than their children.
Algorithm
To solve this, we will follow these steps ?
- n := size of nums
- for i in range 0 to n - 1, do
- left_child := i * 2 + 1 (left child index)
- right_child := i * 2 + 2 (right child index)
- if left_child < n and nums[i] < nums[left_child], then
- return False
- if right_child < n and nums[i] < nums[right_child], then
- return False
- return True
Example
Let us see the following implementation to get better understanding ?
def solve(nums):
n = len(nums)
for i in range(n):
left_child = i * 2 + 1
right_child = i * 2 + 2
# Check left child
if left_child < n:
if nums[i] < nums[left_child]:
return False
# Check right child
if right_child < n:
if nums[i] < nums[right_child]:
return False
return True
# Test the function
nums = [8, 6, 4, 2, 0, 3]
result = solve(nums)
print(f"Is max heap: {result}")
# Test with invalid max heap
nums2 = [8, 10, 4, 2, 0, 3] # 10 > 8, so not a max heap
result2 = solve(nums2)
print(f"Is max heap: {result2}")
Is max heap: True Is max heap: False
How It Works
For any element at index i in the array representation of a heap:
- Left child is at index
2*i + 1 - Right child is at index
2*i + 2 - We check if the parent is greater than both children
- If any parent is smaller than its child, it's not a max heap
Conclusion
This algorithm checks the max heap property by verifying that each parent node is greater than its children. The time complexity is O(n) since we visit each element once.
