
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Is Max Heap in Python?
Suppose we have a list of numbers called nums, we have to check whether it represents a max heap. We will follow these rules −
- nums[i] = nums[2*i + 1] when 2*i + 1 is inside range
- nums[i] = nums[2*i + 2] when 2*i + 2 is inside range
So, if the input is like [5, 3, 4, 1, 2], then the output will be True
To solve this, we will follow these steps −
- for i in range 0 to (size of nums)/2, do
- if nums[i] >= nums[2*i+1] is not true, then
- return False
- if i*2+2 <= (size of nums)-1, then
- if nums[i] >= nums[2*i+2] is not true, then
- return False
- if nums[i] >= nums[2*i+2] is not true, then
- if nums[i] >= nums[2*i+1] is not true, then
- return True
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): for i in range(len(nums)//2): if not nums[i] >= nums[2*i+1]: return False if i*2+2 <= len(nums)-1: if not nums[i] >= nums[2*i+2]: return False return True ob = Solution() nums = [5, 3, 4, 1, 2] print(ob.solve(nums))
Input
[5, 3, 4, 1, 2]
Output
True
- Related Articles
- Program to check heap is forming max heap or not in Python
- Max Heap in Java
- Convert min Heap to max Heap in C++
- Convert BST to Max Heap in C++
- C++ Program to Implement Max Heap
- Minimum element in a max heap in C++.
- Insertion into a Max Heap in Data Structure
- Deletion from a Max Heap in Data Structure
- K-th Greatest Element in a Max-Heap in C++
- What is Heap Sort in Python?
- What is Heap queue (or heapq) in Python?
- Python Heap Queue Algorithm
- Heap queue (or heapq) in Python
- Check if a given Binary Tree is Heap in Python
- max() and min() in Python

Advertisements