Merge 2 Binary Max Heaps

Pattern: Heap implementation

medium

Put the two arrays side by side and build one max heap bottom-up. Building from scratch is O(n + m), which is as fast as anything cleverer, because every value has to be placed anyway.

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

The problem

Given two max heaps as arrays, return one max heap holding all their values. [10, 5, 6, 2] and [12, 7, 9] can give [12, 10, 9, 2, 5, 7, 6].

The catalogue has no practice link for this one. Many arrays are valid answers, so the tests check that your result is a heap holding the same values.

Think first

  • Can you insert the values of one heap into the other?
  • How fast is building a heap from an unordered array?
  • Does the order inside the two inputs help?

Hints

    Brute force, and why it fails

    Insert every value of b into a: O(m log(n + m)).

    The key insight

    Bottom-up building is linear, so joining and rebuilding beats inserting one by one.

    Dry run

    100 
    51 
    62 
    23 
    124 
    75 
    96 

    a = [10, 5, 6, 2], b = [12, 7, 9]. Join them.

    Step 1 of 3

    The plan

    all = a + b
    for i from len(all) / 2 - 1 down to 0: siftDown(all, i)   # max heap
    return all
    

    Complexity

    Time
    O(n + m)
    Space
    O(n + m)

    The joined array is built in linear time; it needs space for all values.

    Edge cases

    • One heap much smaller than the other.
    • Equal values in both.
    • Single values.
    I've built my logic, show the code

    Java

    class Solution {
        public int[] mergeHeaps(int[] a, int[] b) {
            int[] all = new int[a.length + b.length];
            System.arraycopy(a, 0, all, 0, a.length);
            System.arraycopy(b, 0, all, a.length, b.length);   // put the two arrays side by side
            for (int i = all.length / 2 - 1; i >= 0; i--) siftDown(all, i);   // and build one max heap in O(n + m)
            return all;
        }
    
        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:
        vector<int> mergeHeaps(vector<int>& a, vector<int>& b) {
            vector<int> all(a);
            all.insert(all.end(), b.begin(), b.end());          // put the two arrays side by side
            for (int i = static_cast<int>(all.size()) / 2 - 1; i >= 0; i--) siftDown(all, i);   // one max heap in O(n + m)
            return all;
        }
    
        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 mergeHeaps(self, a: list[int], b: list[int]) -> list[int]:
            merged = a + b                          # put the two arrays side by side
            for i in range(len(merged) // 2 - 1, -1, -1):   # and build one max heap in O(n + m)
                self.sift_down(merged, i)
            return merged
    
        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

    • Concatenating without rebuilding: the result is usually not a heap.
    • Building a min heap by mistake.

    Similar problems