Merge Without Extra Space | Practice | GeeksforGeeks

Given two sorted arrays arr1[] and arr2[] of sizes n and m in non-decreasing order. Merge them in sorted order without using any extra space. Modify arr1 so that it contains the first N elements and modify arr2 so that it contains the last M elements. 
 
Example 1:
Input: 
n = 4, arr1[] = [1 3 5 7] 
m = 5, arr2[] = [0 2 6 8 9]
Output: 
arr1[] = [0 1 2 3]
arr2[] = [5 6 7 8 9]
Explanation:
After merging the two 
non-decreasing arrays, we get, 
0 1 2 3 5 6 7 8 9.
Example 2:
Input: 
n = 2, arr1[] = [10, 12] 
m = 3, arr2[] = [5 18 20]
Output: 
arr1[] = [5 10]
arr2[] = [12 18 20]
Explanation:
After merging two sorted arrays 
we get 5 10 12 18 20.



Your Task:
You don't need to read input or print anything. You only need to complete the function merge() that takes arr1, arr2, n and m as input parameters and modifies them in-place so that they look like the sorted merged array when concatenated.
 
Expected Time Complexity:  O((n+m) log(n+m))
Expected Auxilliary Space: O(1)
 
Constraints:
1 <= n, m <= 5*104
0 <= arr1i, arr2i <= 107
0
anilcangulkaya71 day ago
idk what is wrong in this code returns: 1 3 5 7 0 2 6 8 9 :
static int comp(const void* a, const void* b){   return *(int*)&a > *(int*)&b;}
void merge(int arr1[], int arr2[], int n, int m){    //code here   int* temp = malloc(n * 4 + m * 4);      memcpy(temp, arr1, n * 4);   memcpy(temp + n, arr2, m * 4);      qsort(temp, n + m, 4, comp);      memcpy(arr1, temp, n * 4);   memcpy(arr2, temp + n, m * 4);      free(temp);}
+1
navneet05082002kuswaha6 days ago
Striver Gap Method
import mathclass Solution:      #Function to merge the arrays.   def merge(self,arr1,arr2,n,m):                     gap = math.ceil((n+m)/2)              while gap:                      i = 0           j = gap                      while j < (n+m):                              if j < n and arr1[i]>arr1[j]:                   arr1[i],arr1[j] = arr1[j],arr1[i]                                  elif j>=n and i<n and arr1[i]>arr2[j-n]:                   arr1[i],arr2[j-n] = arr2[j-n],arr1[i]                                  elif j>=n and i>=n and arr2[i-n]>arr2[j-n]:                   arr2[i-n],arr2[j-n] = arr2[j-n],arr2[i-n]                              j += 1               i += 1                              if gap == 1:               gap = 0           else:               gap = math.ceil(gap/2) 
-2
haulya1 week ago
        void merge(long long arr1[], long long arr2[], int n, int m)        {            // code here            int i=n-1;           int j = 0;                      while(i >= 0 && j < m){               if(arr2[j] < arr1[i]){                   swap(arr2[j], arr1[i]);                   i--;               }               j++;           }                      sort(arr1, arr1+n);           sort(arr2, arr2+m);       }
0
cshubham4392 weeks ago
 int i = n-1;
        int j = 0;
        while(i>=0 && j<m){
            if(arr1[i]>arr2[j]){
                long temp = arr1[i];
                arr1[i] = arr2[j];
                arr2[j] = temp;
            }
            i--;
            j++;
        }
        Arrays.sort(arr1);
        Arrays.sort(arr2);
0
shubham211019972 weeks ago
simplest solution
void merge(long long arr1[], long long arr2[], int n, int m) 
       { 
          int i=n-1,j=0;
   while(i>=0 && j<m){
       if(arr1[i]>arr2[j]){
           int temp=arr1[i];
           arr1[i]=arr2[j];
           arr2[j]=temp;
       }
       i--;
       j++;
   }
   sort(arr1,arr1+n);
   sort(arr2,arr2+m);
       } 
0
nagasivakrishnav2 weeks ago
Python code very short:
 
def merge(self,arr1,arr2,n,m):       arr1.extend(arr2)       temparr = arr1.copy()       temparr.sort()       arr1.clear()       arr1.extend(temparr[:n])       arr2.clear()       temparr.sort(reverse=True)       arr2.extend(sorted(temparr[:m]))
 
0
artistdarkangel2 weeks ago
BEST JAVA code. 
 
class Solution{  public static void merge(long arr1[], long arr2[], int n, int m)   {      int i=n-1;      int j=0;      while(i>=0 && j<m)      {          if(arr1[i]>arr2[j])          {              long temp=arr1[i];              arr1[i]=arr2[j];              arr2[j]=temp;          }          else           break;          i--;          j++;      }      Arrays.sort(arr1);      Arrays.sort(arr2);  }}
 
0
sagrikasoni2 weeks ago
JAVA SOLUTION
class Solution
{
    //Function to merge the arrays.
    public static void merge(long arr1[], long arr2[], int n, int m) 
    {
      for(int i =0;i<n;i++){
          if(arr1[i]>arr2[0]){
             long temp = arr1[i];
              arr1[i] = arr2[0];
              arr2[0] = temp;
          
       int k =0;
         long first = arr2[0];
         for(k =1;k<m && arr2[k]<first;k++){
             arr2[k-1] = arr2[k];
         }
         arr2[k-1] = first;
      }
    }
}
}
0
geek_deepx3 weeks ago
its showing TLE at 236th test case
my concept was to put smallest element of both the arrays at arr1[i] so i  compared arr1[i] with arr2[0] , because at every step i was sorting arr2 so there will be always smallest element of arr2 at arr2[0].
 
void merge(long long arr1[], long long arr2[], int n, int m)        {            for(int i = 0; i < n; i++) {               if(arr2[0] < arr1[i]){                   swap(arr2[0], arr1[i]);               }               sort(arr2, arr2+m);           }        }
-5
dhruvvsingh223 weeks ago
class Solution{   public:       //Function to merge the arrays.       void merge(long long arr1[], long long arr2[], int n, int m)        {         vector<int>res;         for(int i=0;i<n;i++){           res.push_back(arr1[i]);         }         for(int i=0;i<m;i++){           res.push_back(arr2[i]);         }         sort(res.begin(),res.end());         int k=0;         for(int i=0;i<n;i++)         {           arr1[i] = res[k++];         }         for(int i=0;i<m;i++){           arr2[i] = res[k++];         }       } };
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.