Тёмный

Merge two sorted arrays in O(1) space | GFG | C++ and Java | Brute-Better-Optimal 

take U forward
Подписаться 698 тыс.
Просмотров 307 тыс.
50% 1

Опубликовано:

 

27 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 565   
@takeUforward
@takeUforward 4 года назад
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
@vickythakur5345
@vickythakur5345 4 года назад
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
@deveshvishwakarma23
@deveshvishwakarma23 4 года назад
Understood!!
@himanshukaushik948
@himanshukaushik948 4 года назад
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
@himanshukaushik948
@himanshukaushik948 4 года назад
hence at worst case, complexity is still O(nlogn + mlogm)
@adishijha8365
@adishijha8365 4 года назад
Understood.. Thank you so much for putting in so much effort!!!
@nitantjoshi9903
@nitantjoshi9903 3 года назад
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.
@prakhargupta2737
@prakhargupta2737 3 года назад
Time Complexity ---- Space Complexity 1-O(n+m)log(n+m) O(n+m) 2-O(n+m) O(n+m) 3-O(nm) O(1) 4-O(n+m)log(n+m) O(1)(Gap Method or Shell Short Intuition)
@mallikarjunaiahk431
@mallikarjunaiahk431 2 года назад
3rd one! won't be - Time O(n*mlog(m)) cozz 2nd array requires sorting ! for every element in n!
@abhishekmore5856
@abhishekmore5856 2 года назад
rather than insertion sort (if allowed)we should use priority queue to get smaller element from second array.
@sarthakjoshi21
@sarthakjoshi21 2 года назад
i wanna to know which is the best metod to merge two sorted array (acordding to time complexit and space complexity should be0(1)
@stephenhowe4107
@stephenhowe4107 2 года назад
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?
@sriharshasamayamanthula2692
@sriharshasamayamanthula2692 2 года назад
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
@RAjat9590
@RAjat9590 2 года назад
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
@TannuKumari-yh3pb
@TannuKumari-yh3pb 3 года назад
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 😍
@samirkumar9908
@samirkumar9908 3 года назад
you are in which college?
@georgebell1927
@georgebell1927 2 года назад
Is the sde sheet sufficient for coding rounds of product based companies
@kritikamishra7865
@kritikamishra7865 2 года назад
@@georgebell1927 nope it is sufficient for interviews only ..for coding rounds try arsh goel's sde sheet that helped me a lot
@JujareVinayak
@JujareVinayak Год назад
@@kritikamishra7865 What is difference btw interviews and coding rounds. Coding round is also part of interview.
@adityapatil9215
@adityapatil9215 2 года назад
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
@PabitraPadhy
@PabitraPadhy 2 года назад
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.
@aanchalmittal9897
@aanchalmittal9897 2 года назад
@@PabitraPadhy His answer is based on leetcode problem where size of nums1 = m+n-1 hence its possible
@schrodingerscat6189
@schrodingerscat6189 4 года назад
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..
@prateeksingh6848
@prateeksingh6848 2 года назад
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!
@pranayreddy6337
@pranayreddy6337 3 года назад
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.
@nishantsrivastava2931
@nishantsrivastava2931 3 года назад
yes thats correct...just like merging sorted LL
@bong-techie
@bong-techie 3 года назад
that's ri8, but the obj is to do it in O(1) space, the above approach will take O(m+n) plz correct me if I'm wrong
@madhavkumar-my9zh
@madhavkumar-my9zh 2 года назад
@@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
@diyapathak2413
@diyapathak2413 Год назад
why put it back into the input array tho?
@kailash._11.
@kailash._11. Год назад
@@diyapathak2413 Cause we are supposed to merge in place.
@shredder_plays
@shredder_plays 4 года назад
The intuition behind this is SHELL SORT
@abhi-5783
@abhi-5783 4 года назад
That's helpful. Thanks!
@mukulpanchakarla8944
@mukulpanchakarla8944 4 года назад
is gap algo also called shell sort?
@logic738
@logic738 4 года назад
@@mukulpanchakarla8944 yes
@bhavyaparikh6933
@bhavyaparikh6933 4 года назад
@@mukulpanchakarla8944 yes
@rohitvishwakarma9261
@rohitvishwakarma9261 3 года назад
@@mukulpanchakarla8944 yes
@Aihab1
@Aihab1 3 года назад
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
@av1shekps 3 года назад
It's efficient and easy to implement, really nice. Btw can you tell me where you read about this ?
@Aihab1
@Aihab1 3 года назад
@@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)
@bidiptoroy6350
@bidiptoroy6350 3 года назад
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); }
@shatmanyugupta
@shatmanyugupta 3 года назад
@@bidiptoroy6350 approach is good but not o(1) space, merge sort takes o(n) space
@Red-g1f
@Red-g1f 3 года назад
@@vishalwadhwani6077 your arrays are not sorted atq input arrays should be sorted
@anmolagarwal5952
@anmolagarwal5952 3 года назад
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)
@madhavnagpal1860
@madhavnagpal1860 4 года назад
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); }
@logic738
@logic738 3 года назад
2NlogN
@snehpatel6852
@snehpatel6852 3 года назад
@@logic738 actually nice
@kunaal0403
@kunaal0403 3 года назад
Thats a smart solution.. thanks
@sumitjindal1115
@sumitjindal1115 3 года назад
nice one
@AnkushKumar-mk8ns
@AnkushKumar-mk8ns 3 года назад
Brilliant bro
@janvimahajan8447
@janvimahajan8447 4 года назад
The way you explained the time complexity of each algorithm is just amazing! Thank you 😊
@subhajitdas2379
@subhajitdas2379 4 года назад
O(n*m) will get TLE in GFG. optimize it by thinking how many element of arr2 is needed to be in arr1 then do some operation.
@chinmaynangia4482
@chinmaynangia4482 3 года назад
unable to think kindly give a hint
@kueen3032
@kueen3032 4 года назад
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
@shreyanshnandan9801
@shreyanshnandan9801 3 года назад
This is a LC question.
@shivamnegi4873
@shivamnegi4873 2 года назад
great approach!
@shivangisrivastava1158
@shivangisrivastava1158 4 года назад
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 💫♥️
@arpitmohanty9450
@arpitmohanty9450 4 года назад
Same I follow lovebabber sheet :)
@shuvbhowmickbestin
@shuvbhowmickbestin 2 года назад
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.
@ahishnar1568
@ahishnar1568 3 года назад
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.
@ahishnar1568
@ahishnar1568 3 года назад
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.
@rajatjain1696
@rajatjain1696 3 года назад
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.
@yt_rahul22
@yt_rahul22 3 года назад
can you provide me the code
@vedangfate6290
@vedangfate6290 3 года назад
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
@yashdixit8884
@yashdixit8884 2 года назад
can u share your code
@sgr2683
@sgr2683 4 года назад
Again thank you so much . As a beginner in data structures I am learning too much about time complexity too...😍👍
@ammuubisht
@ammuubisht 3 года назад
Bro you made this problem much more easier and simpler, Thank you so much!
@takeUforward
@takeUforward 3 года назад
Glad it helped!
@ilovemisachan5231
@ilovemisachan5231 2 года назад
Thanks a lot for taking out time to make these lucid explanation videos. Your teaching style is so to-the-point and easy-to-understand.
@nikhilkamboj4376
@nikhilkamboj4376 3 года назад
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
@nikhilsaharan
@nikhilsaharan 2 года назад
We can also perform heapsort which will be O(nlgn) time and O(1) space
@shauryasharma190
@shauryasharma190 Год назад
Good observation if we have to return one array from the two given as output this seems like a very intuitive approach.
@ankitasinha9912
@ankitasinha9912 2 года назад
1st method in js function sort(ar1,ar2){ let s1=ar1.length; let s2=ar2.length; let result=[...ar1,...ar2].sort((a,b)=>a
@gautam4495
@gautam4495 3 года назад
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
@ajaybedre4199
@ajaybedre4199 3 года назад
where u will store the smallest n elements, as we can not use any extra space?
@gautam4495
@gautam4495 3 года назад
@@ajaybedre4199 we can just store two counter variables for that
@ajaybedre4199
@ajaybedre4199 3 года назад
Yaah got it . thanks!!
@anshrastogi3756
@anshrastogi3756 4 года назад
Thank u so much bhaiya for all the things which you have done for us..❤️ Advice : Ignore the haters.
@avinashgupta2308
@avinashgupta2308 3 года назад
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.
@sidharthjain2129
@sidharthjain2129 3 года назад
which year are you from?
@avinashgupta2308
@avinashgupta2308 3 года назад
@@sidharthjain2129 I am in my 2nd year, it just started a month ago
@jaiminsolanki5478
@jaiminsolanki5478 4 года назад
Understood... Please attach Code.. Thankyou for playing such a vital role in making our career!
@written_syntax
@written_syntax 4 года назад
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
@ajaywadhwa3398
@ajaywadhwa3398 3 года назад
Super Clear Cut Explanations !! Really Impressed .
@abhishekkumarsah1917
@abhishekkumarsah1917 4 года назад
You are doing nice work dude! Keep it up would love to see the full series videos as you have mentioned in 30 days of preparation. Really nice work
@takeUforward
@takeUforward 4 года назад
I will try my best
@kumarsaurabhraj2538
@kumarsaurabhraj2538 3 года назад
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.
@ayushranjan3014
@ayushranjan3014 2 года назад
the algo which you are using is called shell sort and it is and optimized way of insertion sort
@prateeksingh6848
@prateeksingh6848 2 года назад
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!
@tanvichandak4102
@tanvichandak4102 2 года назад
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 .
@krishnaanandiswaraa
@krishnaanandiswaraa Год назад
no its not something like in binary search we divide the array but here we are not dividing its already divided
@redBaron_80
@redBaron_80 3 года назад
The second method of swapping elements throws a TLE error in GFG., so ig we need to do with the gap method only
@userre85
@userre85 3 года назад
Cuz many numbers of array have to be shifted while sorting array.
@AnuragKumar-cb5lr
@AnuragKumar-cb5lr 4 года назад
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.
@takeUforward
@takeUforward 4 года назад
how do you shift the elements then? Won't it take O(n)
@sourabhbagrecha
@sourabhbagrecha 3 года назад
Thanks Striver, this video and these comments were very informative, and taught me something new, i.e. GAP method. Thanks again
@udayjordan4262
@udayjordan4262 2 года назад
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
@jatilyadav4000
@jatilyadav4000 Год назад
Amazing Striver. best of luck for future
@ranasauravsingh
@ranasauravsingh 2 года назад
UNDERSTOOD... !!! Thanks striver for the video... :)
@KESHAVKUMAR-qq8im
@KESHAVKUMAR-qq8im Год назад
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.
@web3insiders
@web3insiders 2 года назад
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 ❤.
@vipullohani8
@vipullohani8 4 года назад
For the swap method which was explained before gap method, the time complexity should be n1logn2 and not n1*n2
@takeUforward
@takeUforward 4 года назад
No bro it will be n1*n2
@vipullohani8
@vipullohani8 4 года назад
@@takeUforward for finding the correct position of an element in the sorted array can't it be done in logn time?
@takeUforward
@takeUforward 4 года назад
vipullohani8 but to shift the elements you still have to linearly traverse!
@vipullohani8
@vipullohani8 4 года назад
@@takeUforward yup right
@saketpatel8155
@saketpatel8155 2 года назад
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
@sanheensethi8344
@sanheensethi8344 2 года назад
Gap method is same as Shell Sort, as we also use gap method in that also.
@prateeksingh6848
@prateeksingh6848 2 года назад
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!
@VivekJaviya
@VivekJaviya 2 года назад
I think, Gap Method is actually shell sort if you see properly
@samartajshaikh2601
@samartajshaikh2601 4 года назад
void merge(vector& nums1, vector& nums2) { int i = 0, j = 0; for (; i< nums1.size(); i++) { if (nums1[i] > nums2[j]) { swap(nums1[i], nums2[j]); while (j < nums2.size() && nums2[j] > nums2[j+1]) { swap(nums2[j], nums2[j+1]); j++; } j = 0; } } } merging the two arrays using variation of insertion sort with O(m*n) time complexity.
@uma_918
@uma_918 3 года назад
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.
@rakeshswain4860
@rakeshswain4860 4 года назад
One thing to take care while implementing this is that the GAP size needs to be even every time.
@lokeshdohare4872
@lokeshdohare4872 3 года назад
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.
@prateeksingh6848
@prateeksingh6848 2 года назад
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!
@kalpitmantri17
@kalpitmantri17 Год назад
class Solution { public: void rotate(vector& nums1, int k){ int n = nums1.size(); reverse(nums1, 0, n-1); reverse(nums1, 0, k-1); reverse(nums1, k, n-1); } public: void reverse(vector& nums1, int start, int end){ while(start
@bulukivine8238
@bulukivine8238 3 года назад
Thank you so much striver bhai phli bar me samajh me aa gya
@Sunilkumar-oy6fd
@Sunilkumar-oy6fd 4 года назад
Your explanation is great ! Please make atleast 2 videos per day because this time is placement
@SarthakCodes
@SarthakCodes 2 года назад
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
@subasris7151
@subasris7151 2 года назад
This Gap Algorithm basically uses the intuition of shell sort
@prateeksingh6848
@prateeksingh6848 2 года назад
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!
@pritishpattnaik4674
@pritishpattnaik4674 2 года назад
we can also optimize the first solution by 2 pointer approach
@prateekgautam7398
@prateekgautam7398 4 года назад
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.
@takeUforward
@takeUforward 4 года назад
prateek gautam problem is different, it says you need to put back in a1 and a2, read it properly
@SaurabhSingh-ch6nc
@SaurabhSingh-ch6nc 4 года назад
wow such a crystal clear explanation !
@mansigoyal4796
@mansigoyal4796 4 года назад
you speak with so fluency. please give tips on how you improved your english speaking skills so much.
@mirmohsinali732
@mirmohsinali732 3 года назад
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
@prithvichetty15
@prithvichetty15 3 года назад
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!!
@akarshitgupta6359
@akarshitgupta6359 2 года назад
took 3 hour to implement 3rd solution but finally i did it ..all thanks to neive explanation ... 😄
@suguruchhaya3194
@suguruchhaya3194 3 года назад
(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
@shubhamagarwal2998
@shubhamagarwal2998 3 года назад
nation needs u kind of people
@suguruchhaya3194
@suguruchhaya3194 3 года назад
@@shubhamagarwal2998 thanks:)
@rehithkrishna543
@rehithkrishna543 3 года назад
but we should do it in O(m+n log(m+n)) right?
@gautamsuthar4143
@gautamsuthar4143 3 года назад
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); } }
@tusharjain9701
@tusharjain9701 3 года назад
Gap method is based on sorting circuit
@frustated_fool
@frustated_fool 4 года назад
we can also do a heap sort keeping both the arrays side by side (virtually ofcourse) and adjusting the indices ;-)
@SajidAli-vo8xp
@SajidAli-vo8xp 4 года назад
I think this can be solved using modular arithmetic in o(n1+n2) time using similar approach of auxillary space approach
@swapnaligouda4600
@swapnaligouda4600 3 года назад
The link you provided for the code , it's time complexity and the time complexity u told are different!
@AP-bk8vq
@AP-bk8vq 4 года назад
For the first approach with O(n) space, can't we use two pointers instead of sorting?
@takeUforward
@takeUforward 4 года назад
Yes we can ! I missed that !
@bhupendranagda9563
@bhupendranagda9563 4 года назад
can you explain little bit how can we do that?
@jaydave2500
@jaydave2500 4 года назад
@@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]
@riteshraj1923
@riteshraj1923 4 года назад
@@bhupendranagda9563 same like, we do in merge sort for merging the two parts.
@bhupendranagda9563
@bhupendranagda9563 4 года назад
@@jaydave2500 thanks
@AP-bk8vq
@AP-bk8vq 4 года назад
Understood...thank you sir I was struggling with this one
@stith_pragya
@stith_pragya 2 года назад
Thank You So Much Striver bro.....🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@laxminarayanchoudhary939
@laxminarayanchoudhary939 3 года назад
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.
@prateeksingh6848
@prateeksingh6848 2 года назад
But this algorithm won't work for two unsorted arrays. Can you explain why?
@_hulk748
@_hulk748 Год назад
Thankyou Sir Great Explanation ✨🙏🙇‍♂❤
@mystryb345
@mystryb345 4 года назад
Very good series bro plz keep it up my placement is going on..
@rajankhunt7002
@rajankhunt7002 2 года назад
Shell Sort method use in optimal way.
@divyanshu3149
@divyanshu3149 4 года назад
Understood.. i found this series really helpful
@apoorvamittal4112
@apoorvamittal4112 4 года назад
Thank you for mentioning that you couldn't understand the intuition because I was having a hard time thinking about the logic behind it.
@mailtobasit74
@mailtobasit74 3 года назад
ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-ddeLSDsYVp8.html
@nishantmohanty2147
@nishantmohanty2147 4 года назад
Striver you are a superhuman.After taking 3hrs of class you uploaded a video.
@takeUforward
@takeUforward 4 года назад
6 hours :p
@KB-zg8ho
@KB-zg8ho 4 года назад
@@takeUforward where do you take class bro?
@ajitpatil6532
@ajitpatil6532 2 года назад
This is a great advice that we should try the implementation by ourselves, as I have learned a lot by following this technique.
@champion5946
@champion5946 2 года назад
thankyou bhaiya for all these videos
@sheuly56akter6
@sheuly56akter6 4 года назад
Time : O(n1+n2) Space : O(1) code : paste.ubuntu.com/p/GxCtGqty5t/
@vivekreddy8551
@vivekreddy8551 Год назад
[1,2,4,5,6] [3] for this test case the algorithms fails.....we get [1,2,3,5,4] [6] as the solution...Can you please check?
@rishabhtripathi4002
@rishabhtripathi4002 3 года назад
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)
@shivamjalotra7919
@shivamjalotra7919 2 года назад
Finally you have to sort right ? TC = O(nlogn + mlogm), nice one though
@ritikashishodia675
@ritikashishodia675 2 года назад
Bhaiya two pointer approach to o(n+m) m hoga >> logn*o(n+m)
@utkarshvashisth2793
@utkarshvashisth2793 4 года назад
Bhaiya gap algorithm is inspired from shell sort and shell sort is derived from insertion sort
@takeUforward
@takeUforward 4 года назад
Can you shoot me a link ?
@utkarshvashisth2793
@utkarshvashisth2793 4 года назад
@@takeUforward ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-9crZRd8GPWM.html bhaiya yeh video mein hai expalanation
@utkarshvashisth2793
@utkarshvashisth2793 4 года назад
@@takeUforward ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-SHcPqUe2GZM.html yeh wali thodi short hai video
@ritikeshsharma9953
@ritikeshsharma9953 4 года назад
Thanx for sharing bro The intuition is clear now
@divaynagar1929
@divaynagar1929 4 года назад
You are gonna hit 1 lakh subscribers soon
@random4573
@random4573 3 года назад
I agree with the implementation part
@511-neelbutani9
@511-neelbutani9 3 года назад
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 ?
@paragroy5359
@paragroy5359 3 года назад
Thanks for the playlist sir...
@manubansalcs1003
@manubansalcs1003 4 года назад
We are really exited for your next video Keep it up sir....
@spardha-yug
@spardha-yug 2 года назад
THank you so much striver. God bless you :)
@saisaranya1869
@saisaranya1869 4 года назад
Understood!! Keep Uploading videos daily... :)
@takeUforward
@takeUforward 4 года назад
Surely. One day can be a cheat day :P
@ankurmeena8224
@ankurmeena8224 Год назад
but in gap algorithm we also check for the back algorithm where the are following the order or not
@tekbssync5727
@tekbssync5727 3 года назад
Intuition is -------> *Shell_sort* (or Gap Method) Problem link: practice.geeksforgeeks.org/problems/merge-two-sorted-arrays5135/1
@ashutoshdixit2806
@ashutoshdixit2806 4 года назад
I accidently found your channel and this tuf channel have good s(tuf)fs
@aniket4952
@aniket4952 3 года назад
s(tfu)
@aakankshashivani7707
@aakankshashivani7707 4 года назад
the best explanation, keep going!!
@hetpatel4320
@hetpatel4320 4 года назад
Great work bro, this video series will help lot of people to up skills them selves, thanks for making this video.
@UECRahul
@UECRahul 3 года назад
Thank you sir , your idea to implement code yourself is very good
@sakshamkashyap7329
@sakshamkashyap7329 2 года назад
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
@sukritkapil9816
@sukritkapil9816 3 года назад
excellently explained. thanks!
@harshagarwal1218
@harshagarwal1218 3 года назад
Gfg has o(m+n) soln for this..Is that optimal & good?
@florinmatei8846
@florinmatei8846 3 года назад
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. :-)
@florinmatei8846
@florinmatei8846 3 года назад
the memory needed as work memory for that algo might be a bit bigger, O(N*N)... wow above message I probabily meant N=2^m. Sorry, just me!
Далее
Физика пасты Карбонара 🧪🔬
00:57
Big O Notation, Time Complexity | DSA
21:17
Просмотров 75 тыс.
Sorting Algorithms Explained Visually
9:01
Просмотров 545 тыс.
I Solved 100 LeetCode Problems
13:11
Просмотров 170 тыс.