Implement Max Heap

Pattern: Heap implementation

medium

A max heap in an array: insert appends and sifts up while bigger than the parent; extractMax moves the last item to the top and sifts it down towards the bigger child (the left one when they are equal); changeKey writes the new value and sifts whichever way it needs.

The problem

Build MaxHeap with initializeHeap() (start empty), insert(key), changeKey(index, newVal) (0-based), extractMax() (remove the top, returning nothing), isEmpty(), getMax() and heapSize(). When sinking, if both children are equal, swap with the left one; this matters because changeKey uses positions.

The linked page prints isEmpty as 0 or 1; this guide prints false or true. The tests never read an empty heap.

Think first

  • How is this different from a min heap?
  • Why does the rule for equal children matter here?
  • After changeKey, which way can the value move?

Hints

    Brute force, and why it fails

    Keep the values in a list and scan for the maximum: O(n) for getMax and extractMax.

    The key insight

    The same sift-up and sift-down as a min heap, with the comparisons reversed, keep every operation O(log n).

    Dry run

    100 
    11 
    42 

    initializeHeap(), then insert 4, 1, 10. 10 rises past 4 to the top.

    Step 1 of 4

    The plan

    insert(k):       append k; fix(last)
    extractMax():    a[0] = last; remove last; fix(0)
    changeKey(i, v): a[i] = v; fix(i)
    fix(i):          rise while bigger than the parent
                     then sink while a child is bigger (bigger child, left on ties)
    

    Complexity

    Time
    O(log n) insert, extractMax, changeKey; O(1) others
    Space
    O(n)

    Each fix walks one path.

    Edge cases

    • initializeHeap in the middle of a run clears everything.
    • changeKey on the root.
    • Equal children: the left one moves up.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class MaxHeap {
        private int[] a = new int[4];
        private int n = 0;                          // a[0..n-1] is the heap
    
        public void initializeHeap() {
            n = 0;
        }
    
        public void insert(int key) {
            if (n == a.length) a = Arrays.copyOf(a, 2 * n);
            a[n] = key;
            fix(n++);
        }
    
        public void changeKey(int index, int newVal) {
            a[index] = newVal;
            fix(index);                             // it either rises or sinks, never both
        }
    
        public void extractMax() {
            a[0] = a[--n];                          // the last item fills the top
            if (n > 0) fix(0);
        }
    
        public boolean isEmpty() {
            return n == 0;
        }
    
        public int getMax() {
            return a[0];
        }
    
        public int heapSize() {
            return n;
        }
    
        private void fix(int i) {
            while (i > 0 && a[i] > a[(i - 1) / 2]) {   // rise while bigger than the parent
                swap(i, (i - 1) / 2);
                i = (i - 1) / 2;
            }
            while (true) {                              // sink towards the bigger child
                int l = 2 * i + 1, r = l + 1;
                if (l >= n) return;
                int big = (r < n && a[r] > a[l]) ? r : l;   // equal children: take the left
                if (a[big] <= a[i]) return;
                swap(i, big);
                i = big;
            }
        }
    
        private void swap(int i, int j) {
            int t = a[i]; a[i] = a[j]; a[j] = t;
        }
    }

    C++

    class MaxHeap {
    public:
        vector<int> a;                              // the heap
    
        void initializeHeap() {
            a.clear();
        }
    
        void insert(int key) {
            a.push_back(key);
            fix(static_cast<int>(a.size()) - 1);
        }
    
        void changeKey(int index, int newVal) {
            a[index] = newVal;
            fix(index);                             // it either rises or sinks, never both
        }
    
        void extractMax() {
            a[0] = a.back();                        // the last item fills the top
            a.pop_back();
            if (!a.empty()) fix(0);
        }
    
        bool isEmpty() {
            return a.empty();
        }
    
        int getMax() {
            return a[0];
        }
    
        int heapSize() {
            return static_cast<int>(a.size());
        }
    
        void fix(int i) {
            int n = static_cast<int>(a.size());
            while (i > 0 && a[i] > a[(i - 1) / 2]) {   // rise while bigger than the parent
                swap(a[i], a[(i - 1) / 2]);
                i = (i - 1) / 2;
            }
            while (true) {                              // sink towards the bigger child
                int l = 2 * i + 1, r = l + 1;
                if (l >= n) return;
                int big = (r < n && a[r] > a[l]) ? r : l;   // equal children: take the left
                if (a[big] <= a[i]) return;
                swap(a[i], a[big]);
                i = big;
            }
        }
    };

    Python

    class MaxHeap:
        def __init__(self):
            self.a = []                             # the heap
    
        def initializeHeap(self) -> None:
            self.a = []
    
        def insert(self, key: int) -> None:
            self.a.append(key)
            self.fix(len(self.a) - 1)
    
        def changeKey(self, index: int, new_val: int) -> None:
            self.a[index] = new_val
            self.fix(index)                         # it either rises or sinks, never both
    
        def extractMax(self) -> None:
            last = self.a.pop()
            if self.a:
                self.a[0] = last                    # the last item fills the top
                self.fix(0)
    
        def isEmpty(self) -> bool:
            return not self.a
    
        def getMax(self) -> int:
            return self.a[0]
    
        def heapSize(self) -> int:
            return len(self.a)
    
        def fix(self, i: int) -> None:
            a, n = self.a, len(self.a)
            while i > 0 and a[i] > a[(i - 1) // 2]:     # rise while bigger than the parent
                a[i], a[(i - 1) // 2] = a[(i - 1) // 2], a[i]
                i = (i - 1) // 2
            while True:                                 # sink towards the bigger child
                l, r = 2 * i + 1, 2 * i + 2
                if l >= n:
                    return
                big = r if r < n and a[r] > a[l] else l     # equal children: take the left
                if a[big] <= a[i]:
                    return
                a[i], a[big] = a[big], a[i]
                i = big

    Common mistakes

    • Swapping with the right child on ties, which changes later changeKey results.
    • Forgetting that the inserted value can rise several levels.

    Similar problems