
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Program to check heap is forming max heap or not in Python
- Max Heap in Java
- Convert min Heap to max Heap in C++
- C++ Program to Implement Max Heap
- Convert BST to Max Heap in C++
- Minimum element in a max heap in C++.
- Deletion from a Max Heap in Data Structure
- Insertion into a Max Heap in Data Structure
- What is Heap Sort in Python?
- K-th Greatest Element in a Max-Heap in C++
- What is Heap queue (or heapq) in Python?
- What is Heap Allocation?
- Python Heap Queue Algorithm
- Check if a given Binary Tree is Heap in Python
- Heap queue (or heapq) in Python
Advertisements