Convert Min Heap to Max Heap

Heaps Theory and Implementation Medium
  • The underlying concepts of min-heaps and max-heaps are used prominently in creating priority queues in software development
  • Priority queues are widely used in several real-world applications, like Dijkstra's algorithm for shortest path in graph problems, in load balancing and interrupt handling in an operating system, and in data compression algorithms like Huffman coding
  • The conversion between min-heaps and max-heaps could be beneficial in scenarios where the priority order needs to be reversed or dynamically changed in applications

Given a min-heap in array representation named nums, convert it into a max-heap and return the resulting array.


A 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 the Binary Tree.

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

Examples:

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

Output: [30, 21, 23, 10, 20]

Explanation:

Input: nums = [-5, -4, -3, -2, -1]

Output: [-1, -2, -3, -4, -5]

Explanation:

Input: nums = [2, 6, 3, 100, 120, 4, 5]

Constraints

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

Hints

  • "Start from the last non-leaf node ((n//2) - 1). Apply heapify-down for each node in reverse order. Ensure that every parent is greater than its children by swapping if necessary."
  • "Find the left child at 2*i + 1. Find the right child at 2*i + 2. Swap with the largest child if nums[i] < nums[child]. Recursively heapify down until the heap property is restored."

Company Tags

Activision Blizzard Broadcom Visa Johnson & Johnson Lyft Epic Games Bain & Company Intel Freshworks HCL Technologies Snowflake Splunk Micron Technology Goldman Sachs Rockstar Games Riot Games Electronic Arts Epic Systems Ubisoft Cerner Docker Cloudflare Pinterest Robinhood PayPal Google Microsoft Amazon Meta Apple Netflix Adobe