

You must perform the merge operation in place and must not allocate any extra space to merge the two arrays.
When ‘N’ = 4, ‘A’ = {1, 4, 5, 7} and ‘M’ = 3, ‘B’ = {2, 3, 6}.
We can merge these two arrays into {1, 2, 3, 4, 5, 6, 7} (The elements of ‘A’ are {1, 2, 3, 4} ).
Hence, the answer is {1, 2, 3, 4, 5, 6, 7}.
The first line contains two integers, ‘N’ and ‘M’, denoting the sizes of ‘A’ and ‘B’, respectively.
The second line contains ‘N’ integers denoting the elements of ‘A’.
The third line contains ‘M’ integers denoting the elements of ‘B’.
You must merge the two sorted arrays in place. The smallest ‘N’ elements should be in ‘A’, and the greatest ‘M’ elements should be in ‘B’. You don’t have to return anything. The system will print ‘A’ + ‘B’, where ‘+’ denotes concatenation.
We want to have the ‘N’ smallest elements in ‘A’. For the ‘ith’ smallest elements we can traverse over the remaining positions of ‘A’ and the array ‘B’ to find the minimum elements among them, and then swap that element with ‘A[i]’. Lastly, we sort the array ‘B’.
Here, we will keep the ‘N’ smallest numbers in ‘A’ (not necessarily sorted) and the rest in ‘B’ (not necessarily sorted). We iterate over ‘A’ and ‘B’ using two pointers ‘i’ = 0 and ‘j’ = 0 respectively. If ‘A[i]’ is greater than or equal to ‘B[j]’. We swap some ‘kth’ element of ‘A’ with ‘B[j]’ and increment ‘j’, else we increment ‘i’. It makes sense to always replace the largest elements of ‘A’. Hence, we initialize ‘k’ = ‘N - 1’. Then, we decrement ‘k’ after each swap. Lastly, we sort ‘A’ and ‘B’.
Algorithm: