Implement Max Heap

Heaps Theory and Implementation Medium

You need to implement the Min Heap with the following given methods.

  • insert (x) -> insert value x to the max heap
  • getMax -> Output the maximum value from the max heap
  • exctractMax -> Remove the maximum element from the heap
  • heapSize -> return the current size of the heap
  • isEmpty -> returns if heap is empty or not
  • changeKey (ind, val) -> update the value at given index to val (index will be given 0-based indexing)
  • initializeHeap -> Initialize the heap

Constraints

  • 1 <= n <= 105
  • -105 <= nums[i] <= 105

Hints

  • "Since the maximum value is the largest number stored, it must be found by scanning the heap (worst case O(n)). Alternatively, maintain a secondary max pointer while inserting elements (if extra space is allowed)."
  • "Find the largest value in the heap (brute-force O(n) scan). Swap it with the last element, remove it, and heapify down to restore the min-heap order."

Company Tags

Boston Consulting Group Airbnb McKinsey & Company Rockstar Games Splunk Swiggy Western Digital Roche Byju's MongoDB Ernst & Young Reddit Visa Chewy Unity Technologies JPMorgan Chase Zomato Nutanix Optum Walmart Goldman Sachs PayPal Cloudflare Flipkart Cerner Google Microsoft Amazon Meta Apple Netflix Adobe