Merge Sorted Arrays Without Extra Space | 2 Optimal Solution

Поділитися
Вставка
  • Опубліковано 21 січ 2025

КОМЕНТАРІ • 278

  • @takeUforward
    @takeUforward  Рік тому +29

    Please watch our new video on the same topic: ua-cam.com/video/n7uwj04E0I4/v-deo.html

    • @tanaydhokariya4339
      @tanaydhokariya4339 8 місяців тому

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

    • @purvamjain4953
      @purvamjain4953 5 місяців тому +2

      this is the same video

  • @takeUforward
    @takeUforward  Рік тому +235

    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 UA-cam

    • @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 7 місяців тому

      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 7 місяців тому

      @@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 Рік тому +70

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

    • @iamnoob7593
      @iamnoob7593 6 місяців тому +3

      thanks i am skipping opt 2

    • @AnujJoshi-l8t
      @AnujJoshi-l8t 6 днів тому

      @@iamnoob7593 dont skip it learn what was the though process behind that algorithm .. it would increase your problem solving and logic building approach

  • @utkarshpatil2873
    @utkarshpatil2873 Рік тому +37

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

  • @SydMohan
    @SydMohan Рік тому +29

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

  • @tonystark-oq3mm
    @tonystark-oq3mm Рік тому +21

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

    • @vikasphulriya1841
      @vikasphulriya1841 11 місяців тому +1

      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;
      }
      };

  • @prajnasbhat9059
    @prajnasbhat9059 Рік тому +9

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

  • @babbupatidar8924
    @babbupatidar8924 7 місяців тому +12

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

    • @harshitverma4552
      @harshitverma4552 6 місяців тому +5

      i have the same approch

    • @yashwanthyerra2820
      @yashwanthyerra2820 2 місяці тому

      I don't know about c++,but in java once an array is created its size can't be altered since it is static in size. so its leading to creation of new array which is not the case we required for this question.

    • @yashwanthyerra2820
      @yashwanthyerra2820 2 місяці тому

      if problem is given in such way that nums1 length is upto n+m but it contains m elements then this solution will work:
      int p1 = m-1;
      int p2 = n-1;
      int p = n+m-1;
      while(p1>=0 && p2>=0){
      if(nums1[p1]>nums2[p2]){
      nums1[p] = nums1[p1];
      p1--;
      }
      else{
      nums1[p] = nums2[p2];
      p2--;
      }
      p--;
      }
      while(p2>=0){
      nums1[p] = nums2[p2];
      p2--;
      p--;
      }
      here it comes with time complexity of O(n+m) since no sorting is required in this approach.

    • @babbupatidar8924
      @babbupatidar8924 2 місяці тому

      @@yashwanthyerra2820 this is also a good approach.

  • @lazyemperor5182
    @lazyemperor5182 Рік тому +49

    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

  • @Ayush-wk3vr
    @Ayush-wk3vr 8 місяців тому +6

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

  • @the_avii_7
    @the_avii_7 2 місяці тому +2

    Another Approach:
    TC: O(m*n)
    Explanation:
    1. Iterate over the first array (nums1) and compare every element with nums2 first element (nums2[0]). (Here we are trying to find which element in nums1 array is greater than num2 first element)
    2. The point you found that element (in nums1 array), store it temporary and the replace the original value with the first element of nums2 (nums2[0]).
    3. Now place the temp stored element at the right place in num2 array.
    // rest steps you will understand when you dry run.
    // program.java
    public static void mergeBrute(int[] nums1, int[] nums2) {
    int m = nums1.length;
    int n = nums2.length;
    for (int i = 0; i < m; i++) {
    if (nums1[i] > nums2[0]) {
    // Step 2
    int temp = nums1[i];
    nums1[i] = nums2[0];
    boolean placeAtLast = true;
    // Step 3
    for (int k = 1; k < n; k++) {
    if (temp > nums2[k]) {
    nums2[k - 1] = nums2[k];
    } else if (temp

  • @mehulthuletiya497
    @mehulthuletiya497 Рік тому +11

    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

  • @MohammadAyanKhan-us8vf
    @MohammadAyanKhan-us8vf Рік тому +1

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

  • @HKClasher
    @HKClasher 8 місяців тому +3

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

  • @DeepakKumar-yl3ok
    @DeepakKumar-yl3ok 11 місяців тому

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

  • @crazybro4383
    @crazybro4383 9 місяців тому +1

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

  • @ashishbm3565
    @ashishbm3565 Рік тому

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

  • @tanmaychaudhary2801
    @tanmaychaudhary2801 Рік тому +14

    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.

  • @ErenYeager-dp4er
    @ErenYeager-dp4er 14 днів тому +2

    Done on 7 Jan 2025 at 19:04
    Place : Home
    Leaving for college(train in 2 hours)
    The next time i come to my home town , I hope i would have cracked an internship

  • @AjayKumar-sx6qo
    @AjayKumar-sx6qo Рік тому +1

    Understood. Thank you Striver

  • @soniapadhi7471
    @soniapadhi7471 5 місяців тому

    Content is Absoluetly amazing

  • @Motivationdream99
    @Motivationdream99 Рік тому +2

    Respect++ for striver bhaiya.....

  • @amolgode9843
    @amolgode9843 Рік тому +10

    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 7 місяців тому +1

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

    • @trazz12
      @trazz12 8 днів тому

      sorting will be done in the array itself why it needs extra space?

    • @AnujJoshi-l8t
      @AnujJoshi-l8t 6 днів тому

      because sort fnc uses quick sort .. in quick sort we dont use any extra space

  • @cinime
    @cinime Рік тому

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

  • @VINAYSINGH-wc8sq
    @VINAYSINGH-wc8sq Рік тому

    Best explanation on UA-cam ❤🔥🔥🔥

  • @hackstreet781
    @hackstreet781 Рік тому

    you are a god in programming, man.

  • @ADITYASRIVASTAVABCE
    @ADITYASRIVASTAVABCE Рік тому

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

  • @aryanikale7187
    @aryanikale7187 4 місяці тому

    Lets take a moment to appreciate striver and the person who created this shell sort or gap method

  • @fullycodedtech
    @fullycodedtech Рік тому

    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

  • @abhisheksinghdangi5027
    @abhisheksinghdangi5027 3 місяці тому

    Woho That is so so Cool . THe GAp method is LIT.

  • @DeepakYadav-pm7xn
    @DeepakYadav-pm7xn Рік тому +1

    Very nice explanation🔥

  • @hemendiranbaskaran8463
    @hemendiranbaskaran8463 6 місяців тому +9

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

    • @yashpandey7
      @yashpandey7 4 місяці тому +1

      Merging will allow you to utilize extra space.

    • @shreyxnsh.14
      @shreyxnsh.14 Місяць тому +1

      @@yashpandey7 no it wont

  • @soumiyamuthuraj3516
    @soumiyamuthuraj3516 7 місяців тому

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

  • @sukhpreetsingh5200
    @sukhpreetsingh5200 Рік тому +1

    3rd Approach is amazing

  • @dhivyaviswanathan7604
    @dhivyaviswanathan7604 3 місяці тому

    awesome explanation ever🙂

  • @dawarvaibhav
    @dawarvaibhav Рік тому

    Appreciate the efforts you are putting in 😇

  • @harsha_322
    @harsha_322 Місяць тому

    left,right=len(a)-1,0
    while a[left]>b[right]:
    a[left],b[right]=b[right],a[left]
    left=left-1
    right=right+1
    a.sort()
    b.sort()

  • @rohitkumaram
    @rohitkumaram Рік тому +2

    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.

  • @dipingrover1970
    @dipingrover1970 10 місяців тому

    amazing explanation thanks a lot. 😊

  • @aarishfaiz7880
    @aarishfaiz7880 Місяць тому

    Amazing explanation

  • @deepakmehta4571
    @deepakmehta4571 Рік тому

    Thank you for provide good quality of content

  • @arkanilpaul9501
    @arkanilpaul9501 6 місяців тому

    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 ?

  • @Prabhatsinghrajput-qj3jo
    @Prabhatsinghrajput-qj3jo 5 місяців тому +3

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

  • @ketansarode17
    @ketansarode17 Рік тому

    crystalll clear bhaiya!!!!

  • @DeepakKumar-yl3ok
    @DeepakKumar-yl3ok 11 місяців тому +2

    small issue at 19:54, should have swapped 7 and 6, but that's I guess okay 😅

  • @VikasBishnoi04
    @VikasBishnoi04 Рік тому

    Thank you for great content striver bhaiya ❤

  • @nagame859
    @nagame859 Рік тому

    Understood with ease 🤩..

  • @sourabhsoni5065
    @sourabhsoni5065 2 місяці тому

    Nice explanation.

  • @Shakti_singh96
    @Shakti_singh96 4 місяці тому +1

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

  • @impalash_ag
    @impalash_ag 6 місяців тому +3

    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.

  • @user93-i2k
    @user93-i2k 9 днів тому

    how simple is the second approach, thanks a lot, are you really sure interviewer will accept that?😐

  • @bhishek_
    @bhishek_ 23 дні тому

    14:27, can anyone explain me, why we are not merging the arrays

  • @laxayadharsiniss4759
    @laxayadharsiniss4759 Місяць тому

    A small correction in the video - when you consider gap=3, while comparing 7 with 6, you're missing to swap the elements. Can you please check that once?
    Thanks for the video!

  • @attackgaming9940
    @attackgaming9940 5 місяців тому +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?

  • @yourpeace3801
    @yourpeace3801 10 днів тому

    Maybe i am wrong but -> The swap method assumed that every comparison involved elements from two different arrays (a and b). This caused problems when both indices were from the same array, leading to incorrect swaps and an unsorted result.
    So to overcome this Create another method which will take the single array in which the swapping has to be done. if both indices are in arr1 then pass arr1 along with indices and if both indices are in arr2 pass arr2 along with indices.

  • @hritavsinghsolanki8893
    @hritavsinghsolanki8893 Рік тому +1

    why you did not swap at 19:37?

  • @ReenaSharma-y1o
    @ReenaSharma-y1o Рік тому +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 Рік тому +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)

  • @iamaniket9
    @iamaniket9 11 місяців тому

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

  • @poojakumarisingh5506
    @poojakumarisingh5506 Рік тому

    Thanks a lot striver❤

  • @NazeerBashaShaik
    @NazeerBashaShaik 9 місяців тому

    Understood, thank you.

  • @saaduddin3651
    @saaduddin3651 4 місяці тому

    i guess there are more optimal appraoches like this one
    void merges_sorted_arrays_optimal2(vector &a, vector &b){
    for (int i = 0; i < b.size(); i++)
    {
    a.push_back(b[i]);
    }
    b.clear();
    sort(a.begin(),a.end());
    }

  • @YourCodeVerse
    @YourCodeVerse Рік тому

    Understood✅🔥🔥

  • @MayankSingh-di4ow
    @MayankSingh-di4ow 7 місяців тому +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 5 місяців тому +2

      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

    • @Devil-zr6vk
      @Devil-zr6vk 4 місяці тому

      @@parthkamboj3505 I have also done the problem with this approach

  • @sonukumarnirala6896
    @sonukumarnirala6896 Місяць тому +1

    Thanks gurujii

  • @nayankhuman1043
    @nayankhuman1043 6 місяців тому

    understood :) Thanks a lot.

  • @indian_geocacher
    @indian_geocacher Рік тому +1

    Whats the intutition behind the gap method?

  • @Sillysmiles76
    @Sillysmiles76 Рік тому

    nice explanation,

  • @lingadurai5805
    @lingadurai5805 27 днів тому

    Thank you so much

  • @RiyaSharma-k9p
    @RiyaSharma-k9p Рік тому

    Thank u Striver Understood

  • @itsvinayyay
    @itsvinayyay Рік тому

    Understood!🔥

  • @harshilpatel3205
    @harshilpatel3205 5 місяців тому

    Understood 🙏🏻

  • @AnujJoshi-l8t
    @AnujJoshi-l8t 6 днів тому

    there is a more optimal and easier soln for this problem ..
    though process -- 1--> since nums1 is of m+n size .. there are m elements and n zeroes present in the array .. we can use these zeroes as an extra space
    2-->we need to keep in mind to not to distrupt m elements of nums1 as replacing any element with nums2 elements would lead to data loss
    3--> as the arrays are sorted the best method which should come to mind will be 2 pointers..
    4-->take a random exmaple.. if we start from the first elements of both array then it would lead to loss of m elements of nums[1].. even if we use that extra space which are 0 elements also it would still make things very complicated
    5--> now if things seem complicated from front .. change point of view to backward direction and choose last element and try to put it in its correct position .. as we know last elements willl be largest in both array .. if we put last element in its corrects position which is nums[m+n-1](we keep a third pointer here) there would be two possibility if last element belongs to nums1 or nums2 .. if it belongs to nums1 .. then its a win as we can now distrupt its position and put other element in its earlier position.. if last element belong to num2 still it occupies that extra space and would not distrupt position of nums1 element which is again a win ..
    we an now apply two pointer approach in backward direction starting from the largest element from both arrays (its just like the two pointer u applied in forward direction)..just here we use an extra pointer for keeping elements starting from last and move in bacckward direction .. so its kinda 3 pointer solution
    try out an example to get a good understanding
    i wont write the code as now u can make the code ..
    time complexity worst case--0(m+n)..
    like if it helps

    • @AnujJoshi-l8t
      @AnujJoshi-l8t 6 днів тому

      class Solution {
      public:
      void merge(vector& nums1, int m, vector& nums2, int n) {
      int left = m-1;
      int right = n-1;
      int high = m+n-1;
      while(left>=0 && right>=0){
      if(nums1[left] > nums2[right]){
      nums1[high] = nums1[left];
      left--;
      high--;
      }
      else{
      nums1[high] = nums2[right];
      right--;
      high--;
      }
      }
      while(right >= 0){
      nums1[high] = nums2[right];
      right--;
      high--;
      }

      }
      }; this is the code...u should ignore it and focus on thought process then u can write code easily.. its just for help if anyone wanted

  • @inspiringzone12
    @inspiringzone12 Рік тому

    Excellent Explainaton

  • @studybiz5515
    @studybiz5515 Рік тому +2

    Can you tell me plz when this course complete

    • @takeUforward
      @takeUforward  Рік тому +3

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

  • @sujalgupta6100
    @sujalgupta6100 Рік тому +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 Рік тому

      what approach is to be used there?

  • @schan263
    @schan263 Рік тому

    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.

  • @yogeshjoshi781
    @yogeshjoshi781 8 днів тому

    in the 1st optimized solution, we didnt merge the arrays did we?

  • @prathammishra4964
    @prathammishra4964 Рік тому

    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.

  • @AbjSir
    @AbjSir Рік тому

    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 Рік тому

      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

  • @sayantanpoddar5428
    @sayantanpoddar5428 Рік тому +1

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

  • @her_soulmate
    @her_soulmate Рік тому

    Understood 🎉

  • @kushagraagrawal7690
    @kushagraagrawal7690 Рік тому

    In brute force, if a[left]

  • @bhanderidhruvbhanderidhruv557
    @bhanderidhruvbhanderidhruv557 6 місяців тому

    thank you for expaination

  • @prathamsharma4802
    @prathamsharma4802 Рік тому

    Greak work brother!

  • @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)

  • @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???

  • @songsuniverse4761
    @songsuniverse4761 Рік тому +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--];
    }
    }
    }

  • @dharanyuvi6951
    @dharanyuvi6951 7 місяців тому

    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

  • @rishabh6210
    @rishabh6210 Рік тому

    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

  • @arjavgarg5801
    @arjavgarg5801 4 місяці тому

    What is the intuition for gap method?

  • @sendit9322
    @sendit9322 Рік тому

    understood 👍👍

  • @mukundkumar5088
    @mukundkumar5088 Рік тому

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

  • @pawanshimpi_dev
    @pawanshimpi_dev 3 місяці тому

    If using the gap technique is optimal, then why don't we use it in the mergeSort algorithm where 2 sorted subarrays need to be merged. If we do that, we will be able to bring down the space complexity of mergeSort() from O(N) to O(1).

  • @Shivi32590
    @Shivi32590 7 місяців тому

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

  • @mainakdasgupta7130
    @mainakdasgupta7130 Місяць тому

    Thank you

  • @RAHULROY-sb9nt
    @RAHULROY-sb9nt Рік тому

    pls do complete this series upto ultra advance level.

  • @KirtiRastogi-rf2xd
    @KirtiRastogi-rf2xd 4 місяці тому

    Sir, I am not able to understand timecomplexcity can you make video on timcomplexcity

  • @YadhukrishnanMM-z6k
    @YadhukrishnanMM-z6k Рік тому

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

  • @ad_jha
    @ad_jha 4 місяці тому

    class Solution {
    public:
    void merge(vector& nums1, int m, vector& nums2, int n) {
    int i = m - 1; // Pointer for nums1
    int j = n - 1; // Pointer for nums2
    int k = m + n - 1; // Pointer for the end of nums1
    // Merge in reverse order
    while(i>=0 && j>=0)
    {
    if(nums1[i] > nums2[j]){
    nums1[k--] = nums1[i--];
    }
    else{
    nums1[k--] = nums2[j--];
    }
    }
    // remaining elements in nums2
    while ( j >=0){
    nums1[k--] = nums2[j--];
    }
    }
    };

  • @ifti_taha
    @ifti_taha Рік тому +1

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