In this Leetcode problem, we have to merge two sorted arrays into one.


Image for post

To solve this problem, we are following the min Heap approach. We will be using Priority Queue for that.

A brief about Priority Queue:

PriorityQueue is what is called a binary heap. It is only ordered/sorted in the sense that the first element is the least. In other word, it only cares about what is in the front of the queue, the rest are “ordered” when needed. Therefore, whenever an element is added, it internally heapifies and stores them as per the Comparator function mentioned. By default, it is in ascending order.

Hence the algorithm is as follows:

  1. Create a min Heap and add the elements from the first array to it.
  2. Add the elements from the second array to it.
  3. Remove the elements from the min Heap and add them to the first array thereby replacing the previous values.

Here is the full code:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        for(int i=0;i<m;i++){
            minHeap.add(nums1[i]);
        }

        for(int i=0;i<n;i++){
            minHeap.add(nums2[i]);
        }

        while(!minHeap.isEmpty()){
            for(int i=0;i<m+n;i++){
                nums1[i]=minHeap.remove().intValue();
            }
        }
    }
}

When in doubt, work it out! Happy coding! :)

#java #algorithms #leetcode #coding-interviews #arrays

Leetcode 88: Merge Sorted Array
5.30 GEEK