Implement Min Heap

Pattern: Heap implementation

medium

Store a min heap in a growing array. insert appends and sifts up; extractMin returns a[0], moves the last item to the top and sifts it down; getMin reads a[0]. insert and extractMin are O(log n), the rest O(1).

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Build MinHeap with insert(x), getMin(), extractMin() (remove and return the smallest), size() and isEmpty(). getMin and extractMin return -1 when the heap is empty; that rule is this guide's.

The catalogue had a link here to a page about building a heap from an array, which is a different task, so it was removed.

Think first

  • Where does a new value go first, so the tree stays complete?
  • What can break, and which way does the new value move?
  • After removing the top, what fills the hole?

Hints

    Brute force, and why it fails

    A sorted list gives O(1) getMin but O(n) insert; an unsorted list gives O(1) insert but O(n) extractMin.

    The key insight

    The heap order only links parents and children, so each change is repaired along one path of length log n.

    Dry run

    10 
    41 
    102 

    insert(4), insert(1): 1 rises above 4. insert(10) stays at the bottom.

    Step 1 of 4

    The plan

    insert(x):    append x; sift it up
    extractMin(): if empty: return -1
                  top = a[0]; a[0] = last; remove last; sift a[0] down; return top
    getMin():     a[0] or -1
    

    Complexity

    Time
    O(log n) insert and extractMin, O(1) others
    Space
    O(n)

    Each sift walks one path of the tree.

    Edge cases

    • Extracting the only item.
    • Equal values.
    • Empty heap: -1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class MinHeap {
        private int[] a = new int[4];
        private int n = 0;                          // a[0..n-1] is the heap; the parent of i is (i - 1) / 2
    
        public void insert(int x) {
            if (n == a.length) a = Arrays.copyOf(a, 2 * n);
            a[n] = x;
            int i = n++;
            while (i > 0 && a[(i - 1) / 2] > a[i]) {    // rise while smaller than the parent
                swap(i, (i - 1) / 2);
                i = (i - 1) / 2;
            }
        }
    
        public int getMin() {
            return n == 0 ? -1 : a[0];
        }
    
        public int extractMin() {
            if (n == 0) return -1;
            int min = a[0];
            a[0] = a[--n];                          // the last item fills the hole at the top
            int i = 0;
            while (true) {                          // and sinks to its place
                int l = 2 * i + 1, r = l + 1, small = i;
                if (l < n && a[l] < a[small]) small = l;
                if (r < n && a[r] < a[small]) small = r;
                if (small == i) break;
                swap(i, small);
                i = small;
            }
            return min;
        }
    
        public int size() {
            return n;
        }
    
        public boolean isEmpty() {
            return n == 0;
        }
    
        private void swap(int i, int j) {
            int t = a[i]; a[i] = a[j]; a[j] = t;
        }
    }

    C++

    class MinHeap {
    public:
        vector<int> a;                              // the heap; the parent of i is (i - 1) / 2
    
        void insert(int x) {
            a.push_back(x);
            int i = static_cast<int>(a.size()) - 1;
            while (i > 0 && a[(i - 1) / 2] > a[i]) {    // rise while smaller than the parent
                swap(a[i], a[(i - 1) / 2]);
                i = (i - 1) / 2;
            }
        }
    
        int getMin() {
            return a.empty() ? -1 : a[0];
        }
    
        int extractMin() {
            if (a.empty()) return -1;
            int mn = a[0];
            a[0] = a.back();                        // the last item fills the hole at the top
            a.pop_back();
            int n = static_cast<int>(a.size()), i = 0;
            while (true) {                          // and sinks to its place
                int l = 2 * i + 1, r = l + 1, small = i;
                if (l < n && a[l] < a[small]) small = l;
                if (r < n && a[r] < a[small]) small = r;
                if (small == i) break;
                swap(a[i], a[small]);
                i = small;
            }
            return mn;
        }
    
        int size() {
            return static_cast<int>(a.size());
        }
    
        bool isEmpty() {
            return a.empty();
        }
    };

    Python

    class MinHeap:
        def __init__(self):
            self.a = []                             # the heap; the parent of i is (i - 1) // 2
    
        def insert(self, x: int) -> None:
            a = self.a
            a.append(x)
            i = len(a) - 1
            while i > 0 and a[(i - 1) // 2] > a[i]:     # rise while smaller than the parent
                a[i], a[(i - 1) // 2] = a[(i - 1) // 2], a[i]
                i = (i - 1) // 2
    
        def getMin(self) -> int:
            return self.a[0] if self.a else -1
    
        def extractMin(self) -> int:
            a = self.a
            if not a:
                return -1
            mn = a[0]
            last = a.pop()
            if a:
                a[0] = last                         # the last item fills the hole at the top
                i, n = 0, len(a)
                while True:                         # and sinks to its place
                    l, r, small = 2 * i + 1, 2 * i + 2, i
                    if l < n and a[l] < a[small]:
                        small = l
                    if r < n and a[r] < a[small]:
                        small = r
                    if small == i:
                        break
                    a[i], a[small] = a[small], a[i]
                    i = small
            return mn
    
        def size(self) -> int:
            return len(self.a)
    
        def isEmpty(self) -> bool:
            return not self.a

    Common mistakes

    • Removing the top by shifting the whole array left, which destroys the layout.
    • Forgetting to handle the one-item heap when moving the last item to the top.

    Similar problems