Convert Min Heap to Max Heap

Pattern: Heap implementation

medium

Ignore the min-heap order entirely and build a max heap from the array bottom-up: sift down every non-leaf from n/2 - 1 to 0, always towards the bigger child. That takes O(n).

The problem

Given an array that is a min heap, rearrange it in place into a max heap. [3, 5, 9, 6, 8, 20, 10, 12, 18, 9] can become [20, 18, 10, 12, 9, 9, 3, 5, 6, 8]. The function returns nothing.

Many arrays are valid answers, so the tests check that your result is a heap holding the same values.

Think first

  • Does the min-heap order help build a max heap?
  • Which earlier problem builds a heap from any array?
  • What changes from building a min heap?

Hints

    Brute force, and why it fails

    Sort the array in descending order: a sorted-descending array is a max heap, but sorting costs O(n log n).

    The key insight

    Bottom-up building works on any array, so the input's order does not matter and O(n) is enough.

    Dry run

    30 
    51 
    92 
    63 
    94 
    205 
    106 
    127 
    188 
    89 

    arr = [3, 5, 9, 6, 8, 20, 10, 12, 18, 9]. The last non-leaf is index 4 (8), whose child 9 is bigger: swap.

    Step 1 of 4

    The plan

    for i from n / 2 - 1 down to 0:
        siftDown(arr, i)        # towards the bigger child
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    The same bound as building any heap bottom-up.

    Edge cases

    • One value.
    • All equal: nothing moves.
    • Two values: they swap.
    I've built my logic, show the code

    Java

    class Solution {
        public void convertMinToMaxHeap(int[] arr) {
            for (int i = arr.length / 2 - 1; i >= 0; i--) siftDown(arr, i);   // build a max heap from scratch
        }
    
        private void siftDown(int[] a, int i) {
            int n = a.length;
            while (true) {
                int l = 2 * i + 1, r = l + 1, big = i;
                if (l < n && a[l] > a[big]) big = l;
                if (r < n && a[r] > a[big]) big = r;
                if (big == i) return;
                int t = a[big]; a[big] = a[i]; a[i] = t;
                i = big;
            }
        }
    }

    C++

    class Solution {
    public:
        void convertMinToMaxHeap(vector<int>& arr) {
            for (int i = static_cast<int>(arr.size()) / 2 - 1; i >= 0; i--) siftDown(arr, i);   // build a max heap from scratch
        }
    
        void siftDown(vector<int>& a, int i) {
            int n = static_cast<int>(a.size());
            while (true) {
                int l = 2 * i + 1, r = l + 1, big = i;
                if (l < n && a[l] > a[big]) big = l;
                if (r < n && a[r] > a[big]) big = r;
                if (big == i) return;
                swap(a[big], a[i]);
                i = big;
            }
        }
    };

    Python

    class Solution:
        def convertMinToMaxHeap(self, arr: list[int]) -> None:
            for i in range(len(arr) // 2 - 1, -1, -1):   # build a max heap from scratch
                self.sift_down(arr, i)
    
        def sift_down(self, a: list[int], i: int) -> None:
            n = len(a)
            while True:
                l, r, big = 2 * i + 1, 2 * i + 2, i
                if l < n and a[l] > a[big]:
                    big = l
                if r < n and a[r] > a[big]:
                    big = r
                if big == i:
                    return
                a[big], a[i] = a[i], a[big]
                i = big

    Common mistakes

    • Reversing the array, which is not a max heap in general.
    • Sifting towards the smaller child.

    Similar problems