Please watch the new video which covers it in more depth, and also prints it: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-n7uwj04E0I4.html If you understand the approach, drop "understood" pleaseeeeeee...... The article link where you can find the code has been attached in the description, also do let me know if you want me to attach code in the video or not in the comment section.. . If you appreciate the channel's work, you can join the family: ru-vid.com/show-UCJskGeByzRRSvmOyZOz61igjoin
Everyday I usually start my day with your code Even though I had already practiced this question but lot to come as mentioned in the sheet. But with the ease you tell is something which stuck in the mind. Best explanation bro. Thnx for putting all the efforts. U are already in the best in best company and still helping us . if possible make two videos on two questions in a day. Thnx striver
I have an approach based on my intuition.. How about whenever there is a smaller ele in second array, we swap it with the jth ele in first arr. j=n1-1 initially. After every swap we decrement j. Traversal is from 0 to j in first array. After complete traversal, we soet both the array individually. It works
For the last algorithm, intuition is shell short, which we normally use in place of insertion sort when we know that some of the successive elements are already sorted.
It is good but you should mention stability as a column. Are equal elements from 1st array and 2nd array output in order with all 1st array elements first, 2nd array elements second?
In the third one i think T.C will be O(n*mlogm) because we traverse n length array(O(n)) and every time we swap m length array(O(mlogm)).Please correct me if am wrong
The gap algorithm is generalized insertion sort i.e. shell sort where we initialize gap between elements (here 4) and then reduce the gap until it finally becomes insertion sort at gap=1
Again revising this sheet up to the problem I have completed till now, I thought it will be boring, but I can feel the same excitement while doing every problem which I had felt while doing it the very first time 😍
We can take advantage of ascending sorted arrays. Intuition - We will fill our final answer array from last by taking two pointers i and j which will be pointing first arrays last index and second arrays last index respectively. We will compare the elements at ith and jth index elements of array 1 and array 2 respectively. In comparing whichever will be the greater among them we will put that element at our answer arrays last index and we will decrement the grater element index and answer array index. Likewise we will fill our answer array Implementation - void merge(vector& nums1, int m, vector& nums2, int n) { int i=m-1,j=n-1,k=m+n-1; while(i>=0 && j>=0) { if(nums1[i]>nums2[j]) { nums1[k--]=nums1[i--]; } else { nums1[k--]=nums2[j--]; } } while(j>=0) { nums1[k--]=nums2[j--]; } } //Time Complexity - O(m+n) //Space Complexity - O(1) Note - Here we are storing our answer array in given arr1
Have you tested your code ? so if m = 4 and n = 5 m+n-1 = 8 you're trying to access nums1[8], which is invalid, if your array capacity is not extended. The reason your code works is purely coincidence, due to vector memory allocation. To test my theory.. do this simple test. vector arr{}; // empty vector now try doing arr[1] = 10, you'll understand what I'm trying to say.
the gap method is actually used in shell sort..... here we consider both array place one after other as a single array and then we apply shell sort algorithm to sort it lika a single array........ you can check the shell sort algorithm to get the concept clear..
But in shell sort we apply a loop in reverse direction taking the same gap if there is possibility, but here no such thing is used. Also his algorithm only works for two sorted array, this won't work if the array is unsorted, we have to reverse check also. Also why he is using gap%2, he didn't explain!
The first O(M + N) space approach can be done even better by using 2 pointers and merge algorithm of merge sort and then putting them back in input arrays. Total time will be 2 * O(M + N) and we can avoid the sorting part.
@@bong-techie this approach will also take O(1) space what we will do is firstly we will shift all the elements of first array to right and then merge both using 2 pointers
Another efficient method: Traverse the first array backwards and the second array forwards while swapping (if element from second array is smaller than first array). After that, sort the arrays 1&2. Time Complexity: O(NlogN + MlogM)
@@av1shekps I had this question in the Geeks for Geeks 11 Weeks DSA Workshop and it was marked under "hard" category. Apparently I was able to solve it using this technique (without any help) (took some time tho :D)
Thank you: code of your idea: Java public static void merge(long arr1[], long arr2[], int n, int m) { int i = n-1; int j = 0; while(i>=0 && jarr2[j]) { long temp = arr1[i]; arr1[i] = arr2[j]; arr2[j] = temp; } i--;j++; } Arrays.sort(arr1); Arrays.sort(arr2); }
This is shell sort & the intuition behind shell sort is merge sort Basically dividing array in two halves and sorting them Then half the halves & merge them Then do it again and again until half becomes 1 in size (so it cannot be halved)
this idea works and is much simpler void merge(int one[], int two[], int sizeOne, int sizeTwo) { int i=sizeOne-1, j = 0; while(i>=0 and jtwo[j]) swap(one[i],two[j]); i--,j++; } sort(one,one+sizeOne); sort(two,two+sizeTwo); }
A similar question to this, more like easy version of this, so we can attend linear time complexity in below question: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. Example: Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Constraints: -10^9
You explain the best, Striver✔️😍. Do not stop and complete the series ASAP. I feel so dependent on your sheet bcz i have seen the responses over your SDE sheet. Lots of love to you 💫♥️
I also came up with a solution of my own where I picked the maximum element from the first array and the minimum element from the second. In case the maximum element was greater than the minimum element from the second array then in that case the numbers would be swapped and then the maximum and minimum elements would be updated with the new values(if need be). The solution gave correct array but they were not sorted henceforth I had to sort both of them separately essentially giving a O((n + m)log(n + m)) time complexity and a 0(1) space complexity.
If we closely look at gap algorithm then it is actually working like a merge sort. While going down in this algorithm on LHS of gap we will have all smaller elements and on RHS of gap we will have greater elements. Now that left and right array we have to sorted and so off course we have to reduce the gap to mid of that left array and for right array mid of right array and do the same thing till gap not equal to 1. And we are possible to do this because both the arrays are sorted. Just look closely, we can observe that gap algorithm is similar to merge sort algorithm only.
Even we can sort any unsorted array with this gap algorithm. And if we use gap algorithm then we can sort array in NlogN time and O(1) space which is better than O(N) space in merge sort.
We can also do the first approach in O(N) time & O(N) space complexity. Find the minimum element among the current two elements of both the arrays and update the output_array with the least value and increment its index to next position.
This seems to be the most efficient approach. I think the solution discussed in the video is only for the case if the interviewer asks us to do the task in O(1) space complexity
hi with gap method conceptually work in similar manner two step that are missing only that lead little confusion apply gap on first and second array also algo will look like 1.gap(array1) 2.gap(array1,array2) 3.gap(array2) earlier when i study gap method from another channel i got confused why it's not sorting properly. Great work keep it up
one algorithm I can think of is: find n smallest elements in the two arrays using two pointers, then add all those in the first array. then sort both arrays, in this way we could do i in o(nlogn) with o(1) space
What I was thinking, the intuition behind the gap method was merge sort, We are considering both the array as one single array and trying to apply merge sort here > The first gap was sum of length of both the arrays divided by two i.e we are calculating the mid of that assumed single array > For every iteration we are doing gap/2 i.e again finding another mid > As soon as gap/2 becomes 0 we just stopped reason we don't run merge sort on a single element of a array gap = 0 stands for single element. Actually I tried applying merge sort assuming them as a single array and while watching the solution I just related my approach to this. I might be wrong. These all were my assumption.
It should work but can be optimize : #include using namespace std; int main() { int n,m,i,t,j; cin>>n>>m; int arr1[n+1],arr2[m+1]; for(i=0;i>arr1[i]; for(i=0;i>arr2[i]; i=0; while(i!=n) { while(arr1[i]arr2[j] && j
In the insertion sort method, Why is re-arrangement never needed in the first array? For any element in the first array, the element before it could have been swapped with the first element of the second array or could not have been swapped. If the second array the first element would always be the smallest element at that point of time as we are doing the re-arrangement in the second array after swaps. If the element previous to the current element was swapped then the element we get at its position after swapping would be less than the original element because that's our criteria for swapping, if the element next to it in the first array is not swapped then the first array stays sorted as the next element was greater than the original previous element and a smaller element came in its place after sorting. Or if the next element is swapped then also the first array would stay sorted because then next element that came after swapping would be greater than the previous element that came by swapping as the first element in the second array is always the smallest in that array and new elements that come in the second array are always greater than older elements. However, if the previous element in the first array was not swapped, then that was because it was less than the first element in the second array, otherwise it would have been swapped so even if the element next to it is swapped, it will be greater than the previous element and sorting in the first array would be preserved.
But in shell sort we apply a loop in reverse direction taking the same gap if there is possibility, but here no such thing is used. Also his algorithm only works for two sorted array, this won't work if the array is unsorted, we have to reverse check also. Also why he is using gap%2, he didn't explain!
I think the intuition for this should be similar to binary, we are dividing it in two parts , so it's like dividing same problem into smaller problems by considering our both arrays as a single array, and then we keep on doing this till size of each divided array is one and sorting it also simultaneously by swapping. If you think it like merge sort .
We can solve this problem in NlogN by using binary search. Whenever we swap the element we will search that element exact position at second array and insert it into second array. And also whenever we swap the second array will become the another problem based on binary search is Rotated sorted array.
if you are using extra space still it can be done with a O(N) t.c no need for sorting just using two pointer method it can be done but yeah the problem is regarding space but brute force should be O(n) t.c then go for space
I think the intution behind gap method is devid and conquer. Because each time performing operation over a range and then diving it into half and reperforming it.
Sir you are a god for cp and dsa , thanks for being existed on youtube no one cant even come closer you when it comes to your way of explanation , thanks you so much sir ❤.
another nlog(n) approach with intution (gfg merge without extra space problem ) : void merge(long long arr1[], long long arr2[], int n, int m) { int i=0,j=0; while(i+j
But in shell sort we apply a loop in reverse direction taking the same gap if there is possibility, but here no such thing is used. Also his algorithm only works for two sorted array, this won't work if the array is unsorted, we have to reverse check also. Also why he is using gap%2, he didn't explain!
When I gave the insertion sort approach. Interviewer is not happy. The insertion sort approach can be improved if I come from the ending of smaller array and use thos extra spaces.
Why is it so? Suppose initially our gap size is 14, then after half, it becomes 7. So what we will do, we will take 6 or 8. May be that's why my I'm getting wrong answer.
But what's the reason?? Everyone just says the algorithm, like they are just memorising! Nobody explains. But in shell sort we apply a loop in reverse direction taking the same gap if there is possibility, but here no such thing is used. Also his algorithm only works for two sorted array, this won't work if the array is unsorted, we have to reverse check also. Also why he is using gap%2, he didn't explain!
Understood .... The question you linked to leetcode is not exactly this one so if anyone who is trying to work out with the optimal code in the article has to make changes to it as the question in leetcode is variation of this one
But in shell sort we apply a loop in reverse direction taking the same gap if there is possibility, but here no such thing is used. Also his algorithm only works for two sorted array, this won't work if the array is unsorted, we have to reverse check also. Also why he is using gap%2, he didn't explain!
I'm sorry I might be wrong but in your first explanation you created the a3 and then put all sorted elements back to a1 and a2 depending upon the size, but this is not "merging" merging means we need to create 3rd array which is combination of both and sorted, Of course you know this but in 1st explanation you could have stopped at a3.
This is how I did it using 2 pointers in C++ using the second approach you showed. Thank you so much #include #include using namespace std; int main() { int a[] = {1,4,7,8,10}; int b[] = {2,3,9}; int aSize = sizeof(a) / sizeof(a[0]); int bSize = sizeof(b) / sizeof(b[0]); int i,j; int *p1 = a; int *p2 = b; while(p1 != &a[aSize]) { if(*p1 > *p2) { swap(*p1,*p2); sort(b,b + bSize); } else { p1++; } } for (i = 0; i < aSize; i++) { cout
sir your channel is far more the best channel for DSA preparation but if you can please also explain the code like in earlier videos because it just makes the concept crystal clear I agree with your point of view but if you at least please can attach the relevant code in java as I am java developer it would be great help!! thank you for amazing explanation Big Fan!!
(Crazy long comment but I think there is a lot of value!) I will explain the difference between striver's approach and the editorial of this question on geeksforgeeks: practice.geeksforgeeks.org/problems/merge-two-sorted-arrays-1587115620/1#editorial There are 2 main differences. First notice this. Striver chooses to iterate over arr1. You must ask yourself, "What is going on in arr1 and how is it different from what is going on in arr2?" Answer: In arr1, smallest elements are placed IN THE CORRECT POSITION from the left side and the array gets SORTED NATURALLY. In arr2, a value from arr1 is just "dumped" and striver has to sort it manually. Based on this fact, can't we say that similar approach of placing largest values from the end of arr2 will also be a similar achievement? Instead of locking in the smallest values, we can also choose to lock in the largest values, right? YES! The geeksforgeeks solution 1. Iterates from the end of the array (because largest values need to be placed at end) and 2. Iterates over arr2 instead of arr1 (because larger values need to be place in arr2). The iteration direction and which array to iterate over go hand in hand because they are related. On to the second difference. Striver immediately swaps elements in arr1 and arr2 to "lock in" the small values in arr1. He then uses a while loop to figure out where to the correct placement should be, insert the element, and deletes the initial value that was simply "dumped". When you examine the editorial solution on geeksforgeeks, it doesn't immedaitely swap the values from arr1 and arr2. Instead it iterates over arr1, finds the correct location to insert the element from arr2, inserts the element, and modifies arr2 as well. (study the editorial if this is confusing). Basically the difference here is whether to swap then adjust to correct position (striver) and find correct position and swap (geeks for geeks editorial). Either can work. Based on the above ideas, I came up with a total of 4 different approaches. 1. Iterate arr1 from the beginning. Swap, then adjust. (striver's approach) 2. Iterate arr1 from the beginning. Find correct position, then swap. 3. Iterate arr2 from the end. Swap, then adjust. 4. Iterate arr2 from the end. Find correct position, then swap. (editorial's approach). I wrote Python 3 code for these 4 approaches here: github.com/SuguruChhaya/python-tutorials/blob/master/Data%20Structures%20and%20Algorithms/mergewithoutextrafinal.py
what's wrong in my code? Please reply. void swap(int a,int b){ int temp=a; a=b; b=temp; } void merge(int arr1[], int arr2[], int n, int m) { //code here int gap=ceil((n+m)/2); while(gap>0){ int i=0; int j=i+gap; while(jarr2[j-n]){ swap(arr1[i],arr2[j-n]); } } else if(i>=n+m){ if(arr2[i-n]>arr2[j-n]){ swap(arr2[i-n],arr2[j-n]); } } i++;j++; } gap=ceil(gap/2); } }
@@bhupendranagda9563 Take two pointers say i,j here i points to first ele. of a1 array and j points to first point of a2 arraay...now we wiil check if(a1[i]
Nice. initially, I got doubt that why he is CEILING the gap value then I get to know that if we don't use ceil here it will skip some gap value like(ie..2) gap=3 -> gap/=2 (ie. gap=1 ) here we need gap = 2. Thanks.
I have my own solution to this problem. In the first method discussed in the video, we don't need to sort the entire second array each time, instead we just need that the least element must be at zeroth index of second array. This is just like how a heap works. So we can heapify the second array each time we perform the swap operation. So in this way we can correctly assign values to first array. The second array may not be sorted but we can sort it using inbuilt sort method. In this way we can solve this problem in O(nlogn)
Does the interviewer ask to write a code or...just we need to explain the approach ...and if he ask to write a code...then where we have to write (paper ) or any ide ?
Simple soultion *Time complexity : O(m+n), Space Complexity : O(1)* void merge(vector& nums1, int m, vector& nums2, int n) { int left = m - 1, right = n - 1, k = nums1.size(); while(right >= 0) { while(left >=0 && right >=0 && nums2[right] < nums1[left]) nums1[--k] = nums1[left--]; nums1[--k] = nums2[right--]; } for(auto i : nums1) cout
Now a problem: lets say we got an array of N=2^N random numbers. Could we use an algo based on simulated processing to try to solve for the proof that algo is correctly doing its job. I mean , for fun, and if it is possible, of course. Indication:for each O(1) step of this algo, we could try to track the way of how those numbers reach their right place. :-)