Check if an array represents a min heap

Heaps Theory and Implementation Medium
  • Fun Fact: Binary min-heaps play a critical role in various data-intensive applications in the software industry
  • They are particularly effective in designing priority queues and implementing algorithms like Dijkstra's shortest path
  • Also, in the network sector, binary min-heaps help to handle bandwidth management and packet scheduling in Internet routers
  • Thus, a function that determines the validity of a binary min-heap can act as a useful debugging tool in these scenarios, ensuring that the underlying data structure is correctly organized and functional

Given an array of integers nums. Check whether the array represents a binary min-heap or not. Return true if it does, otherwise return false.


A binary min-heap is a complete binary tree where the key at the root is the minimum among all keys present in a binary min-heap and the same property is recursively true for all nodes in a Binary Tree.

Examples:

Input: nums = [10, 20, 30, 21, 23]

Output: true

Explanation: Each node has a lower or equal value than its children.

Input: nums = [10, 20, 30, 25, 15]

Output: false

Explanation: The node with value 20 has a child with value 15, thus it is not a min-heap.

Input: nums = [1, 2, 1, 3]

Constraints

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • The array represents a complete binary tree.

Hints

  • "A binary min-heap is stored in array form, where: Parent of i is at (i-1) // 2. Left child of i is at 2*i + 1. Right child of i is at 2*i + 2."
  • "To check if nums is a valid min-heap: Iterate through all parent nodes (indices 0 to (n//2) - 1). Compare each parent with its left and right children (if they exist). If any parent is greater than a child, return False."

Company Tags

Philips Healthcare OYO Rooms Cerner Optum KPMG Mastercard Target Alibaba Square Ubisoft Roche Seagate Technology Byju's Goldman Sachs eBay Ernst & Young Zoho Siemens Healthineers Splunk Freshworks Flipkart PwC Johnson & Johnson MongoDB DoorDash Google Microsoft Amazon Meta Apple Netflix Adobe