Is Max Heap in Python?

PythonServer Side ProgrammingProgramming

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
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

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
raja
Published on 22-Sep-2020 11:18:17
Advertisements