Time limit exceed!

Question : Merge two sorted array without extra space;
https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays/0

My approach;
i used second array B as a min heap. For each element in A (size n) , i compared it with
B[0], if i A[i] is greater than B[0] each time ,then i swapped it. and maintained my min heap B (size m) ( using make_heap in log m);

so my complexity should be n*logm and with given constraints ( n,m < 5x10^4) my code should calculate in < 1sec ??

My code:
https://ide.geeksforgeeks.org/Yr4HETM2nS

1 Like

You are rebuilding the heap in each step which is O(m log m) each step making the overall complexity O(mn log m). The correct way to do this is in each step, first pop the minimum element from the heap and then push the new element (which is either the same element or the current a[i]). Popping and pushing both take O(log m) time and thus the complexity becomes O(n log n).

1 Like

U can actually do this in O(m+n) to get the expected output.

Clue

use 2 iterators one for each array to traverse.

Explanation

start from 0 index for both arrays, output the element that is smaller then increment the iterator corresponding to that array.
At last output the remaining elements that are left out.
p.s. U can use vectors and clear to use 0 space

Code
  1. void solve1()
    
  2. {
    
  3.     int n,m;cin>>n>>m;
    
  4.     int arr[n],brr[m];
    
  5.     for(int i=0;i<n;i++)
    
  6.     {
    
  7.         cin>>arr[i];
    
  8.     }
    
  9.     for(int i=0;i<m;i++)
    
  10.     {
    
  11.         cin>>brr[i];
    
  12.     }
    
  13.     int i=0,j=0;
    
  14.     while(i<n&&j<m)
    
  15.     {
    
  16.         if(arr[i]>brr[j])
    
  17.         {cout<<brr[j]<<" ";j++;}
    
  18.         else
    
  19.         {cout<<arr[i]<<" ";i++;}
    
  20.     }
    
  21.     while(i<n)
    
  22.     {
    
  23.         cout<<arr[i]<<" ";i++;
    
  24.     }
    
  25.     while(j<m)
    
  26.     {
    
  27.         cout<<brr[j]<<" ";j++;
    
  28.     }cout<<endl;
    
  29. }
    
1 Like

This helped me.

Thanks

thanks for reply. appreciate ur suggestion .
In this question. outputs are the modified arrays itself.
so we need to find a way to modify both arrays and get desired two output arrays.

thanks man.