Given two sorted integer arrays, merge them into a single array in decreasing order, and return it. In other words, merge two sorted arrays from their end.

For example,

Input:
 
X = [1, 3, 5]
Y = [2, 6, 7]
 
Output: [7, 6, 5, 3, 2, 1]
 
 
Input:
 
X = [1, 4, 7, 8]
Y = [2, 3, 9]
 
Output: [9, 8, 7, 4, 3, 2, 1]

Practice this problem

We can easily solve this problem iteratively. There are many cases to deal with – either X or Y may be empty during processing, either X or Y can run out first, and finally, there is a challenge of starting the result array empty, and building it up while traversing X and Y in reverse order.

Following is the C++, Java, and Python implementation that handles all these cases:

C++


Download  Run Code

Output:

First Array : 1 4 7 8
Second Array: 2 3 9
After Merge : 9 8 7 4 3 2 1

Java


Download  Run Code

Output:

First Array : [1, 4, 7, 8]
Second Array: [2, 3, 9]
After Merge : [9, 8, 7, 4, 3, 2, 1]

Python


Download  Run Code

Output:

First Array : [1, 4, 7, 8]
Second Array: [2, 3, 9]
After Merge : [9, 8, 7, 4, 3, 2, 1]

The time complexity of the above solution is O(m + n), where m and n are the total number of elements in the first and second array, respectively.