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.
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]
This problem is similar to building heap from a given array. The fact that the given array is a min-heap array can be overlooked, boiling down the problem to building a Max-heap array from the given array.
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
// Function to recursively heapify the array downwards
void heapifyDown(vector<int> &arr, int ind) {
int n = arr.size(); // Size of the array
// To store the index of largest element
int largestInd = ind;
// Indices of the left and right children
int leftChildInd = 2*ind + 1, rightChildInd = 2*ind + 2;
// If the left child holds larger value, update the largest index
if(leftChildInd < n && arr[leftChildInd] > arr[largestInd])
largestInd = leftChildInd;
// If the right child holds larger value, update the largest index
if(rightChildInd < n && arr[rightChildInd] > arr[largestInd])
largestInd = rightChildInd;
// If the largest element index is updated
if(largestInd != ind) {
// Swap the largest element with the current index
swap(arr[largestInd] , arr[ind]);
// Recursively heapify the lower subtree
heapifyDown(arr, largestInd);
}
return;
}
public:
// Function to convert a min-heap array to a max-heap array
vector<int> minToMaxHeap(vector<int> nums) {
int n = nums.size();
// Iterate backwards on the non-leaf nodes
for(int i = n/2 - 1; i >= 0; i--) {
// Heapify each node downwards
heapifyDown(nums, i);
}
return nums;
}
};
// Driver code
int main() {
vector<int> nums = {10, 20, 30, 21, 23};
cout << "Initial Min-heap Array: ";
for(int x : nums) cout << x << " ";
// Creating an object of the Solution class
Solution sol;
// Function call to convert a min-heap array to a max-heap array
nums = sol.minToMaxHeap(nums);
cout << "\nMax-heap converted Array: ";
for(int x : nums) cout << x << " ";
return 0;
}
import java.util.*;
class Solution {
// Function to recursively heapify the array downwards
private void heapifyDown(int[] arr, int ind) {
int n = arr.length; // Size of the array
// To store the index of largest element
int largestInd = ind;
// Indices of the left and right children
int leftChildInd = 2*ind + 1;
int rightChildInd = 2*ind + 2;
// If the left child holds larger value, update the largest index
if(leftChildInd < n && arr[leftChildInd] > arr[largestInd]) {
largestInd = leftChildInd;
}
// If the right child holds larger value, update the largest index
if(rightChildInd < n && arr[rightChildInd] > arr[largestInd]) {
largestInd = rightChildInd;
}
// If the largest element index is updated
if(largestInd != ind) {
// Swap the largest element with the current index
int temp = arr[largestInd];
arr[largestInd] = arr[ind];
arr[ind] = temp;
// Recursively heapify the lower subtree
heapifyDown(arr, largestInd);
}
}
// Function to convert a min-heap array to a max-heap array
public int[] minToMaxHeap(int[] nums) {
int n = nums.length;
// Iterate backwards on the non-leaf nodes
for(int i = n/2 - 1; i >= 0; i--) {
// Heapify each node downwards to ensure max-heap property
heapifyDown(nums, i);
}
return nums;
}
}
class Main {
public static void main(String[] args) {
int[] nums = {10, 20, 30, 21, 23};
System.out.print("Initial Min-heap Array: ");
for(int x : nums) {
System.out.print(x + " ");
}
// Creating an object of the Solution class
Solution sol = new Solution();
/* Function call to convert the given
array from min-heap to max-heap */
nums = sol.minToMaxHeap(nums);
System.out.print("\nMax-heap converted Array: ");
for(int x : nums) {
System.out.print(x + " ");
}
}
}
class Solution:
# Function to recursively heapify the array downwards
def _heapifyDown(self, arr, ind):
n = len(arr) # Size of the array
# To store the index of largest element
largestInd = ind
# Indices of the left and right children
leftChildInd = 2*ind + 1
rightChildInd = 2*ind + 2
# If the left child holds larger value, update the largest index
if leftChildInd < n and arr[leftChildInd] > arr[largestInd]:
largestInd = leftChildInd
# If the right child holds larger value, update the largest index
if rightChildInd < n and arr[rightChildInd] > arr[largestInd]:
largestInd = rightChildInd
# If the largest element index is updated
if largestInd != ind:
# Swap the largest element with the current index
arr[largestInd], arr[ind] = arr[ind], arr[largestInd]
# Recursively heapify the lower subtree
self._heapifyDown(arr, largestInd)
return
def minToMaxHeap(self, nums):
n = len(nums)
# Iterate backwards on the non-leaf nodes
for i in range(n//2 - 1, -1, -1):
# Heapify each node downwards
self._heapifyDown(nums, i)
return nums
def main():
nums = [10, 20, 30, 21, 23]
print("Initial Min-heap Array: ", end="")
for x in nums:
print(x, end=" ")
# Creating an object of the Solution class
sol = Solution()
# Function call to convert the given array from min-heap to max-heap
nums = sol.minToMaxHeap(nums)
print("\nMax-heap converted Array: ", end="")
for x in nums:
print(x, end=" ")
if __name__ == "__main__":
main()
class Solution {
// Function to recursively heapify the array downwards
heapifyDown(arr, ind) {
let n = arr.length; // Size of the array
// To store the index of largest element
let largestInd = ind;
// Indices of the left and right children
let leftChildInd = 2*ind + 1;
let rightChildInd = 2*ind + 2;
// If the left child holds larger value, update the largest index
if(leftChildInd < n && arr[leftChildInd] > arr[largestInd]) {
largestInd = leftChildInd;
}
// If the right child holds larger value, update the largest index
if(rightChildInd < n && arr[rightChildInd] > arr[largestInd]) {
largestInd = rightChildInd;
}
// If the largest element index is updated
if(largestInd !== ind) {
// Swap the largest element with the current index
[arr[largestInd], arr[ind]] = [arr[ind], arr[largestInd]];
// Recursively heapify the lower subtree
this.heapifyDown(arr, largestInd);
}
return;
}
// Function to convert the min-heap array to max-heap array
minToMaxHeap(nums) {
let n = nums.length;
// Iterate backwards on the non-leaf nodes
for(let i = Math.floor(n/2) - 1; i >= 0; i--) {
// Heapify each node downwards
this.heapifyDown(nums, i);
}
return nums;
}
}
// Driver code
function main() {
let nums = [10, 20, 30, 21, 23];
process.stdout.write("Initial Min-heap Array: ");
for(let x of nums) {
process.stdout.write(x + " ");
}
// Creating an object of the Solution class
let sol = new Solution();
// Function call to convert the given array from min-heap to max-heap
nums = sol.minToMaxHeap(nums);
process.stdout.write("\nMax-heap converted Array: ");
for(let x of nums) {
process.stdout.write(x + " ");
}
}
// Run the driver code
main();
Time Complexity: O(N) (where N is the number of elements in the array)
Each heapify call has a time complexity of O(h), where h is the height of the subtree, h = log(N). The heapify operation is performed for approximately N/2 non-leaf nodes.
Due the variable height for all the subtrees, summing the total work done for all the nodes results in an overall time complexity of O(N) for building a heap.
Space Complexity: O(logN)
The recursive calls during heapify require stack space proportional to the height of the heap which will be of the order of log(N) in the worst-case.
Q: Why do we start heapifying from (n//2) - 1 instead of 0?
A: Leaf nodes (from n//2 onward) are already valid heaps (no children to compare). Only non-leaf nodes need to be heapified down.
Q: Why does this work in-place without extra space?
A: Since both min-heap and max-heap use the same array structure, we only modify values in-place.
Q: How would you modify this to convert a max-heap into a min-heap?
A: Apply heapify-down in reverse order (swap with the smallest child instead of the largest).
Your notes are automatically saved in your browser's local storage and will persist across sessions on this device.