Ninja has been given two sorted integer arrays/lists ‘ARR1’ and ‘ARR2’ of size ‘M’ and ‘N’. Ninja has to merge these sorted arrays/lists into ‘ARR1’ as one sorted array. You may have to assume that ‘ARR1’ has a size equal to ‘M’ + ‘N’ such that ‘ARR1’ has enough space to add all the elements of ‘ARR2’ in ‘ARR1’.
For example:
‘ARR1’ = [3 6 9 0 0]
‘ARR2’ = [4 10]
After merging the ‘ARR1’ and ‘ARR2’ in ‘ARR1’.
‘ARR1’ = [3 4 6 9 10]
Input Format
The first line of input contains an integer ‘T’ which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains two space-separated integers ‘M’ and ‘N’, which represent the size of ‘ARR1’ and ‘ARR2’.
The next lines of each test case contain ‘M’ space-separated integers and ‘N’ zeros (i.e. 0) which represent the number of elements in ‘ARR1’.
The next lines of each test case contain ‘N’ space-separated integers which represent the number of elements in ‘ARR2’.
Output Format :
For each test case, return the ‘ARR1’ after merging.
Print the output of each test case in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= ‘T’ <= 100
1 <= ‘M’, ‘N’ <= 5000
1 <= ‘ARR1[i], ARR2[i]’ <= 100000
Time Limit: 1 second
A simple approach would be to create a new arrays with size as sum of the sizes of both the arrays. Copy the elements of both the arrays in the new array and sort the array.
A space optimised approach...read more
Our main task is that after merging ‘ARR2’ into ‘ARR1’. The resultant ‘ARR1’ is also sorted. So first we simply add all the elements of ‘ARR2’ into ‘ARR1’. Then we can apply any sorting alg...read more
As we know both ‘ARR1’ and ‘ARR2’ are sorted. So we can declare two variables ‘i’ and ‘j’ and initialize ‘i’ with ‘M’ and ‘j’ with ‘N’. Then we compare the last element of both arrays/l...read more
// Online Javascript Editor for free
// Write, Edit and Run your Javascript code using JS Online Compiler
a = [1,2 ,4, 7,9, 11, 19]
b = [4,7,8,9,10,11]
c = []
j=0
i=0
k = a.length + b.length - 1
wh...read more
Top Rakuten Software Developer interview questions & answers
Popular interview questions of Software Developer
Reviews
Interviews
Salaries
Users/Month