Merge Sorted Arrays Without Extra Space | 2 Optimal Solution

Поделиться
HTML-код
  • Опубликовано: 25 авг 2024

Комментарии • 219

  • @takeUforward
    @takeUforward  11 месяцев назад +22

    Please watch our new video on the same topic: ruclips.net/video/n7uwj04E0I4/видео.html

    • @tanaydhokariya4339
      @tanaydhokariya4339 3 месяца назад

      😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊

    • @purvamjain4953
      @purvamjain4953 6 дней назад +1

      this is the same video

  • @takeUforward
    @takeUforward  Год назад +175

    Do give us a like, it won't cost you anything :), but it will motivate me to make more and more.

    • @akshay_gudi
      @akshay_gudi Год назад +2

      Hi striver, I have a doubt on optimal solutions that besides having higher time complexities than brute force how can they be optimal? Also memory is cheaper these days and time is considered most valuable. Please tell me how to respond if the interviewer asks me this question?

    • @hariommishra4547
      @hariommishra4547 Год назад

      Thank you striver bhaiya for providing quality content in RUclips

    • @Hello_world-s5z
      @Hello_world-s5z Год назад

      hi striver in the 2nd optimal approach i.e. when left and right are in same array does our swap function will work properly ???

    • @FooBar-lb5wf
      @FooBar-lb5wf 2 месяца назад

      The standard Shell sort performs insertion sort at different interval values. However, in the second optimal solution to this problem, for each interval, we just swap the adjacent values (separated by interval), which isn't exactly the same as doing insertion sort. The optimal solution, however, still works well. I understand that intuitively this works because the two individual arrays are already sorted. However, I couldn't really find a proof that this approach always yields the correct solution. Any pointers are much appreciated, Thanks.

    • @kaizoku8771
      @kaizoku8771 2 месяца назад

      @@FooBar-lb5wf The method used in this video is comb sort not shell sort. In comb sort we perform bubble sort with gaps. In shell sort we perform insertion sort with gaps.

  • @Manishgupta200
    @Manishgupta200 Год назад +47

    The first optimal is very easy to understand compare to second optimal aproach. Both way are totally understable. Thankyou

    • @iamnoob7593
      @iamnoob7593 Месяц назад +1

      thanks i am skipping opt 2

  • @utkarshpatil2873
    @utkarshpatil2873 Год назад +30

    It's really good to see how much teaching skills you have improved. Thanks!

  • @lazyemperor5182
    @lazyemperor5182 Год назад +25

    This is probably my 10th time here and I still always forget the intuition and trick to the besr optimzd approach to this problem, it's a tough problem

  • @prajnasbhat9059
    @prajnasbhat9059 10 месяцев назад +9

    Thank you Striver for providing detailed videos on DSA. Really appreciate your work!

  • @tonystark-oq3mm
    @tonystark-oq3mm Год назад +17

    What an Explanation Striver Bro! The Gap method is really amazing.

    • @vikasphulriya1841
      @vikasphulriya1841 6 месяцев назад

      bro i am trying to sort an array using Shell sort
      can you tell what problem does this code have
      class Solution {
      public:
      vector sortArray(vector& nums) {
      int n=nums.size();
      int gap=(n/2)+(n%2);
      while(gap>0){
      int left=0;
      int right=0+gap;
      while(rightnums[right])swap(nums[left],nums[right]);
      left++;right++;
      }

      if(gap==1)break;
      gap=(gap/2)+(gap%2);
      }
      return nums;
      }
      };

  • @user-cj3zr7pu7t
    @user-cj3zr7pu7t Год назад +23

    So far the clearest explanation I could find for the gap method. Thanks a lot!!

  • @hemendiranbaskaran8463
    @hemendiranbaskaran8463 Месяц назад +4

    my simple approach is
    1. merge two arrays
    2. sort once the final array - to get answer

  • @MayankSingh-di4ow
    @MayankSingh-di4ow 2 месяца назад +3

    As per the leetcode problem where zeroes are given in array-1
    Another Approach: Fill from behind, when zeroes are exhausted, start filling from front.
    then reverse arr[0 to m] and arr[0 to m+n]
    void merge_fillFromBehind(vector& nums1, int m, vector& nums2, int n) {
    if(n==0) return;

    int i=0, j=0, k=(n+m-1);
    while(i

    • @parthkamboj3505
      @parthkamboj3505 8 дней назад +1

      I think more easier approach would be to take three pointers as:
      i points to the last valid element in nums1 (at index m-1).
      j points to the last element in nums2 (at index n-1).
      k points to the last position in nums1 (at index m + n - 1).
      Compare the elements at i and j and place the larger one at index k. Then move the corresponding pointer (i or j) and k backward.
      After finishing the loop, if any elements are left in nums2, copy them into nums1. This happens because nums1 might already be sorted and have smaller elements at the beginning.
      while (i >= 0 && j >= 0) {
      if (nums1[i] > nums2[j]) {
      nums1[k] = nums1[i];
      i--;
      } else {
      nums1[k] = nums2[j];
      j--;
      }
      k--;
      }
      // If there are still elements left in nums2, copy them
      while (j >= 0) {
      nums1[k] = nums2[j];
      j--;
      k--;
      }
      Happy Coding

  • @tanmaychaudhary2801
    @tanmaychaudhary2801 Год назад +13

    Thank you bhaiya for providing quality content....I am from tier 3 and I want to work with reputed companies like Google, Amazon, uber, Microsoft etc... within 2 years .... currently I am about to complete 3rd year BTech CSE.

  • @crazybro4383
    @crazybro4383 4 месяца назад +1

    Optimal solution 2 was really good and your teaching skills made it easier and interesting

  • @amolgode9843
    @amolgode9843 7 месяцев назад +7

    HIi Bro
    If we use built in sort()
    then How can we say it solved in constant space??
    Because sort() will also need O(N) Space internally right?

    • @kaizoku8771
      @kaizoku8771 2 месяца назад +1

      Isn't the sort function based on a variation of quick sort? Which might take O(logN) stack space to execute?

  • @Prabhatsinghrajput-qj3jo
    @Prabhatsinghrajput-qj3jo 13 дней назад +2

    can we consider this as optimal approach ??
    public static void merge(int []a,int []b,int n){
    int left = 0;
    while(left

  • @mehulthuletiya497
    @mehulthuletiya497 Год назад +9

    00:40 Problem Statement
    01:55 Brute force approach
    04:43 Code
    08:52 Complexity
    09:53 Optimal - 1
    12:50 Code
    13:51 Complexity
    15:37 Optimal - 2
    15:52 Gap Method
    24:40 Code
    30:59 Complexity

  • @babbupatidar8924
    @babbupatidar8924 2 месяца назад +1

    class Solution {
    public:
    void merge(vector& nums1, int m, vector& nums2, int n) {
    for(int i=0; i

  • @DeepakKumar-yl3ok
    @DeepakKumar-yl3ok 6 месяцев назад

    Thank you Striver for making these in-depth very well explained videos

  • @Motivationdream99
    @Motivationdream99 Год назад +2

    Respect++ for striver bhaiya.....

  • @ashishbm3565
    @ashishbm3565 9 месяцев назад

    bhai aap genius ho!!.. real inspiration and best teacher to me...

  • @MohammadAyanKhan-us8vf
    @MohammadAyanKhan-us8vf 11 месяцев назад

    your quality of teaching,frameworks and style of teaching all are superb sir💯

  • @rohitkumaram
    @rohitkumaram 7 месяцев назад +1

    Thanks a lot:
    can we include this O(m+n) solution:
    just start from the back and keep adding the greater one from both sides:
    it will fill sorted.

  • @soniapadhi7471
    @soniapadhi7471 23 дня назад

    Content is Absoluetly amazing

  • @soumiyamuthuraj3516
    @soumiyamuthuraj3516 2 месяца назад

    awesome, short of words to thank you really. making a v big impact n my coding life.

  • @sukhpreetsingh5200
    @sukhpreetsingh5200 Год назад +1

    3rd Approach is amazing

  • @cinime
    @cinime Год назад

    Understood! Super amazing explanation as always, thank you very very very much for your effort!!

  • @HKClasher
    @HKClasher 3 месяца назад +1

    //Two line solution for(int i=0;i

  • @attackgaming9940
    @attackgaming9940 17 дней назад +1

    Can someone tell me the which of the optimal approach has better complexity in case of time or Both of'em are somewhat equal?

  • @AjayKumar-sx6qo
    @AjayKumar-sx6qo Год назад +1

    Understood. Thank you Striver

  • @sujalgupta6100
    @sujalgupta6100 7 месяцев назад +1

    you can't apply optimal 1 to leetcode problem because they give nums1 of m + n size , so when you sort zeroes would come first
    and after merging actual nums1 data will be erased.

    • @shreyxnsh.14
      @shreyxnsh.14 7 месяцев назад

      what approach is to be used there?

  • @hackstreet781
    @hackstreet781 8 месяцев назад

    you are a god in programming, man.

  • @Shivi32590
    @Shivi32590 2 месяца назад

    LeetCode solution: class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
    int r=n-1;
    for(int i=m;i

  • @ADITYASRIVASTAVABCE
    @ADITYASRIVASTAVABCE Год назад

    Appreciate the efforts you are putting in. Content is Absoluetly amazing.

  • @impalash_ag
    @impalash_ag Месяц назад +1

    Hi Raj,
    How come the 1st optimal solution be optimal solution at all, when sorting method itself takes O(log n) of extra space? And, because of this the TC of 1st optimal solution is worse than Brute Force solution but the SC is better.

  • @DeepakYadav-pm7xn
    @DeepakYadav-pm7xn Год назад +1

    Very nice explanation🔥

  • @user-sn3im6cn7e
    @user-sn3im6cn7e 8 месяцев назад +1

    @takeUforward shouldn't the time complexity of the brute force solution be O(m) as for traversal of both the arrays simultaneously, it would be O(n) and O(m-n) for traversal of the remaining larger array, so overall TC would be O(n)+O(m-n)=O(m). Please clarify, it would be of great help @striver

    • @Fe-ironman
      @Fe-ironman 7 месяцев назад +1

      no look at the worst case:-
      for eg:- arr1=[1,2,3] arr2=[4,5,6,7] in this case you will first traverse through entire arr1 then afterwards you traverse through entire arr2 so TC=O(m+n)

  • @Shakti_singh96
    @Shakti_singh96 12 часов назад

    in first optimal approach , we are modifying both the array , but we have to merge both the array , pls explain

  • @varunshikhwal5916
    @varunshikhwal5916 Год назад +2

    the optimal 1 code :
    #include
    #include
    #include
    void mergeTwoSortedArraysWithoutExtraSpace(vector &a, vector &b)
    {
    long long n=a.size();
    long long m=b.size();
    int left=n-1;
    int right=0;
    while(left>=0 && rightb[right]){
    swap(a[left],b[right]);
    left--;
    right++;
    }
    else break;
    }
    std::sort(a.begin(),a.end());
    std::sort(b.begin(),b.end());
    }

  • @dipingrover1970
    @dipingrover1970 5 месяцев назад

    amazing explanation thanks a lot. 😊

  • @songsuniverse4761
    @songsuniverse4761 11 месяцев назад +3

    Why would we do so much if we can just put everything on the second array in the first one and apply the sort function ?
    The time complexity will be the same : O(n+m) * log(n+m)
    The better solution with O(n+m) time complexity is
    void merge(vector& nums1, int m, vector& nums2, int n) {
    int i = m - 1;
    int j = n - 1;
    int k = m + n - 1;

    while (j >= 0) {
    if (i >= 0 && nums1[i] > nums2[j]) {
    nums1[k--] = nums1[i--];
    } else {
    nums1[k--] = nums2[j--];
    }
    }
    }

  • @deepakmehta4571
    @deepakmehta4571 Год назад

    Thank you for provide good quality of content

  • @Ayush-wk3vr
    @Ayush-wk3vr 3 месяца назад

    In gap method when the gap is 3 why do you don't swap 7 and 6.(7>6) 20:03

  • @fullycodedtech
    @fullycodedtech 11 месяцев назад

    00:06 Merge two sorted arrays without extra space
    04:09 The problem with the approach is using an extra array.
    08:21 Implementing a Brute Force solution to sort two arrays in the correct order
    12:31 Sorting arrays using a two-pointer approach
    16:52 Comparison algorithm for moving pointers based on a decreasing Gap
    20:58 Implement the Gap method to arrange elements in ascending order.
    24:56 Implement swap function to ensure left is always at array 1
    29:13 Understanding the code for adjusting 'left' and 'right' in an array

  • @schan263
    @schan263 10 месяцев назад

    The sorting could take extra space depending on the programming language being used. I use Python and Python uses Timsort which uses extra space for sorting.

  • @VINAYSINGH-wc8sq
    @VINAYSINGH-wc8sq Год назад

    Best explanation on RUclips ❤🔥🔥🔥

  • @dawarvaibhav
    @dawarvaibhav Год назад

    Appreciate the efforts you are putting in 😇

  • @VikasBishnoi04
    @VikasBishnoi04 Год назад

    Thank you for great content striver bhaiya ❤

  • @ketansarode17
    @ketansarode17 Год назад

    crystalll clear bhaiya!!!!

  • @harshilpatel3205
    @harshilpatel3205 17 дней назад

    Understood 🙏🏻

  • @ifti_taha
    @ifti_taha Год назад +1

    Striver Sir You should have solved leetcode problem that's difficulty level is greater than this !

  • @nayankhuman1043
    @nayankhuman1043 Месяц назад

    understood :) Thanks a lot.

  • @dharanyuvi6951
    @dharanyuvi6951 2 месяца назад

    But the thing is
    If we go for the optimal 2 approach
    Its more like giving us NLogN time complexity which is same as any other sorting mechanisms
    Which is we are using the sorted arrays as advantage but couldn't replicate that in complexity wise
    just for saving spaces - we did over engineering i suppose on this aspect

  • @harharmahadev3115
    @harharmahadev3115 Год назад +2

    Brother, please complete it as soon as possible.

    • @takeUforward
      @takeUforward  Год назад +16

      Yes bro, just not wanting to compromise on the quality.

    • @ayushdhiman8128
      @ayushdhiman8128 Год назад

      @@takeUforward please do take your time but do not compromise the quality thats what it is helpful to us students

  • @NazeerBashaShaik
    @NazeerBashaShaik 4 месяца назад

    Understood, thank you.

  • @nagame859
    @nagame859 Год назад

    Understood with ease 🤩..

  • @RAHULROY-sb9nt
    @RAHULROY-sb9nt Год назад

    pls do complete this series upto ultra advance level.

  • @user-ui9fw7qj5n
    @user-ui9fw7qj5n 7 месяцев назад

    Thank u Striver Understood

  • @indian_geocacher
    @indian_geocacher Год назад +1

    Whats the intutition behind the gap method?

  • @studybiz5515
    @studybiz5515 Год назад +2

    Can you tell me plz when this course complete

    • @takeUforward
      @takeUforward  Год назад +2

      The entire syllabus is there on the website, you can do it at your own pace, don't wait for me

  • @DeadPoolx1712
    @DeadPoolx1712 5 дней назад

    UNDERSTOOD;

  • @bhanderidhruvbhanderidhruv557
    @bhanderidhruvbhanderidhruv557 2 месяца назад

    thank you for expaination

  • @sayantanpoddar5428
    @sayantanpoddar5428 9 месяцев назад +1

    GOD LEVEL EXPLAIN!!!!!!...... please came up with string playlist.!!!!!!!

  • @CodewithKing360
    @CodewithKing360 2 месяца назад +2

    Optimal understood but leetcode not accepted solutina

  • @AniketKumar-hf2bo
    @AniketKumar-hf2bo 6 месяцев назад

    thnx for the amazing video ❤❤❤❤👌👌👌👌

  • @priyotoshsahaThePowerOf23
    @priyotoshsahaThePowerOf23 Год назад +1

    class Solution {
    public:
    void swapIfGreater(vector&nums1,vector&nums2, int ind1,int ind2)
    {
    if(nums1[ind1] > nums2[ind2])
    swap(nums1[ind1],nums2[ind2]);
    }
    void merge(vector& nums1, int m, vector& nums2, int n) {
    int len = (m+n);
    int gap= (len/2) + (len%2);
    while(gap>0)
    {
    int left=0 ;
    int right=left+gap;
    while(right < len) // not out of bound
    {
    // arr1 ,arr2
    if(left=n)
    {
    swapIfGreater(nums1,nums2, left, right-n);
    }
    // arr2,arr2
    else if(left>=n)
    {
    swapIfGreater(nums2,nums2, left-n, right-n);
    }
    else
    {
    swapIfGreater(nums1,nums1, left, right);
    }
    left++ , right++;
    }
    if(gap==1) // for reamining iterations
    break;
    gap=(gap/2)+(gap%2);

    }

    }
    };
    what is the problem in this code .. test cases not passing???

  • @prathammishra4964
    @prathammishra4964 7 месяцев назад

    i have a question regarding first optimal solution its total space complexity is O(1) but why it is O(1) in our solution we performed sorting of both the arrays but in context of java when use Arrays.sort() it internally uses tim sort which is derives from insertion sort and merge sort which has a time complexity of O(n) so why we are including this space in our solution.

  • @inspiringzone12
    @inspiringzone12 Год назад

    Excellent Explainaton

  • @poojakumarisingh5506
    @poojakumarisingh5506 11 месяцев назад

    Thanks a lot striver❤

  • @Sillysmiles76
    @Sillysmiles76 Год назад

    nice explanation,

  • @shashankgsharma0901
    @shashankgsharma0901 Месяц назад

    Understood.

  • @surajvalluru
    @surajvalluru Год назад +1

    In gap method....
    When gap = 3, we compared 7 & 6 and didn't swap them.

  • @sahilbagate1505
    @sahilbagate1505 Год назад

    Thinks so found a new optimal approach:
    Time complexity: O(m+n)
    Code:
    class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
    nums1[m:] = []
    i = 0
    j = 0
    while i < m and j < n:
    if nums1[i] > nums2[j]:
    nums1.insert(i, nums2[j])
    j += 1
    m += 1
    else:
    i += 1
    while j < n:
    nums1.append(nums2[j])
    j += 1

    • @poojanpatel354
      @poojanpatel354 Год назад

      not O(m+n) because when you insert in array it is O(n) complexity which will make your solution O(mn + n^2)

  • @anonymoustechdot9598
    @anonymoustechdot9598 14 дней назад

    where is the proof of second optimal solution that the algo works?
    how did we make sure that it works and how did it was figured out?

  • @hritavsinghsolanki8893
    @hritavsinghsolanki8893 Год назад +1

    why you did not swap at 19:37?

    • @vijayragav85
      @vijayragav85 10 месяцев назад

      Yesss.... why he didn't swap that

  • @prathamsharma4802
    @prathamsharma4802 11 месяцев назад

    Greak work brother!

  • @golakotisowmya4075
    @golakotisowmya4075 5 месяцев назад

    gap method solution not working in javascript because first time when gap =1 it should execute loop for adjacent elements for once. If gap =1, break the loop going forward . Let me know if I am wrong or any other best possible way.

  • @kushagraagrawal7690
    @kushagraagrawal7690 Год назад

    In brute force, if a[left]

  • @ameerhamzakhan2851
    @ameerhamzakhan2851 4 месяца назад

    in optimal first approach i think inbuilt sort use some memory so space is not O(1)

    • @saswatrath4646
      @saswatrath4646 4 месяца назад

      while using sort function you take into account only the time complexity, which is N logN, the space complexity is O (1).

    • @kaizoku8771
      @kaizoku8771 2 месяца назад

      @@saswatrath4646 why is that? I read somewhere that sort is based on a variation of quick sort which might take O(logN) stack space

  • @itsvinayyay
    @itsvinayyay Год назад

    Understood!🔥

  • @stat_life
    @stat_life 11 месяцев назад +3

    LEETCODE NOT ACCEPTING OPTIMAL SOLUTION 1
    left = n - 1
    right = 0
    # Swap the elements until arr1[left] is smaller than arr2[right]:
    while left >= 0 and right < m:
    if arr1[left] > arr2[right]:
    arr1[left], arr2[right] = arr2[right], arr1[left]
    left -= 1
    right += 1
    else:
    break
    # Sort arr1[] and arr2[] individually:
    arr1.sort()
    arr2.sort()

    • @Alokankit627
      @Alokankit627 4 месяца назад +1

      what i see that here in optimal code 1 we basically just sorting both of the arrays but not merging them to one sorted array
      🤔

  • @YourCodeVerse
    @YourCodeVerse 9 месяцев назад

    Understood✅🔥🔥

  • @her_soulmate
    @her_soulmate 9 месяцев назад

    Understood 🎉

  • @GungunRamchandani
    @GungunRamchandani Месяц назад

    Understood

  • @rishabh6210
    @rishabh6210 10 месяцев назад

    do we really nead to sort for the optimal 1? I think we can just reverse the 2nd half of 1 array and merge it with the first half

  • @user-rc2ds4cy8f
    @user-rc2ds4cy8f Год назад

    one of the main constraint was the array must be without extra spaces......so its unclear whether we need to take one 0 or enitrely skip 0

  • @Abc-rz4ps
    @Abc-rz4ps Месяц назад

    in case gap is odd , take the ceiling

  • @riddlemastermind25
    @riddlemastermind25 5 месяцев назад

    Understood!

  • @ganeshaghav3808
    @ganeshaghav3808 17 дней назад

    Is this course available in udemy

  • @rahulhembram4519
    @rahulhembram4519 Год назад

    UNDERSTOOD

  • @AbjSir
    @AbjSir 10 месяцев назад

    If shell sort has worst case complexity O(n^2) then how does the optimal2 solution complexity is nlogn it is also just basically sorting the imaginary combined array right?

    • @AbjSir
      @AbjSir 10 месяцев назад

      Answer: Time complexity of shell sort depends on how you choose the gaps apparently so it"s not a fixed algorithm it can be of O(nlogn) too if you choose gaps this way
      I think there is a rule as to how youre supposed to choose gaps but that is not required I think as shell sort is not that important it seems

  • @sendit9322
    @sendit9322 Год назад

    understood 👍👍

  • @605_samikrdas4
    @605_samikrdas4 Год назад +6

    Better Approach ngl:
    class Solution {
    public:
    void merge(vector& nums1, int m, vector& nums2, int n) {
    int i = m - 1;
    int j = n - 1;
    int k = m + n - 1;

    while (j >= 0) {
    if (i >= 0 && nums1[i] > nums2[j]) {
    nums1[k--] = nums1[i--];
    } else {
    nums1[k--] = nums2[j--];
    }
    }
    }
    };

  • @arkanilpaul9501
    @arkanilpaul9501 Месяц назад

    Why is it not needed to swap 7 and 6 at 19:59 ? 7 is greater than 6, so we must swap 7 and 6. Or am I getting anything wrong ?

    • @qjayant
      @qjayant Месяц назад

      yup idk why nobody noticed this

    • @MohammadEhshan-ve6uz
      @MohammadEhshan-ve6uz 26 дней назад

      he has motioned below that he has done a mistake

  • @kaizoku8771
    @kaizoku8771 2 месяца назад

    The gap method explained in this video is not entirely correct. When gap becomes 1 we have to perform the iterations with gap = 1 up until our array is sorted. If we break away after only 1 iteration then it is possible that our array is not fully sorted.

  • @user-ut9sj2kf4j
    @user-ut9sj2kf4j 8 месяцев назад

    is it okay that first i merge both array and applied insertion sort

  • @younusshaik1685
    @younusshaik1685 Год назад

    tq tq very much

  • @varunpalsingh3822
    @varunpalsingh3822 Год назад

    understood 👍

  • @mukundkumar5088
    @mukundkumar5088 Год назад

    Namaste bhaiya , last bit of code is not working properly.
    could you please help me to do that .

  • @sauravchandra10
    @sauravchandra10 Год назад

    why do we need two optimal approaches, when one gets the work done?

  • @abhijeetmishra3804
    @abhijeetmishra3804 10 месяцев назад

    superb

  • @angadmanroy4658
    @angadmanroy4658 8 дней назад

    Linear time which ig should be better the nlogn in method 2
    void merge(vector& nums1, int m, vector& nums2, int n) {
    int i = m - 1;
    int j = n - 1;
    int k = m + n - 1;

    while (j >= 0) {
    if (i >= 0 && nums1[i] > nums2[j]) {
    nums1[k--] = nums1[i--];
    } else {
    nums1[k--] = nums2[j--];
    }
    }
    }