Heapify Algorithm

Heaps Theory and Implementation Medium

Given an array nums representing a min-heap and two integers ind and val, set the value at index ind (0-based) to val and perform the heapify algorithm such that the resulting array follows the min-heap property.

Modify the original array in-place, no need to return anything.

Constraints

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • 0 <= ind < nums.length
  • -104 <= val <= 104
  • nums represents a min-heap

Hints

  • "Compare the node with its parent at parent = (ind-1) // 2. If nums[ind] < nums[parent], swap them and move up recursively. Stop when ind == 0 (root) or no more violations exist."
  • "Compare the node with its left child at 2*ind + 1 and right child at 2*ind + 2. Swap with the smallest child if nums[ind] is greater. Recursively move down until heap property is restored."

Company Tags

Swiggy Robinhood Flipkart Walmart Intel Texas Instruments Western Digital Byju's Teladoc Health Freshworks Cerner NVIDIA Chewy GE Healthcare Bloomberg Target Unity Technologies Zynga Lyft Bungie KPMG Docker PwC American Express Deloitte Google Microsoft Amazon Meta Apple Netflix Adobe