Given two integer arrays, each of which is sorted in increasing order, merge them into a single array in increasing order, and return it.

For example,

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

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.

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

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

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

Python


Download  Run Code

Output:

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

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.