Median of Two Sorted Arrays - Binary Search - Leetcode 4

  Рет қаралды 482,744

NeetCode

NeetCode

Күн бұрын

Пікірлер: 578
@NeetCode
@NeetCode 3 жыл бұрын
🚀 neetcode.io/ - A better way to prepare for Coding Interviews
@stupidfrog
@stupidfrog 9 ай бұрын
Easily the hardest LC problem I've ever come across to date. This solution makes sense, but there is no way anyone is coming up with this in a 45 min interview lol
@AndreiSokolov-k7j
@AndreiSokolov-k7j 8 ай бұрын
what does an interview even entail? They want an employee who has experience in a certain field and they test it with tasks. Yes, it's a difficult task, but it just shows whether you've had experience of problem solving in general. If there weren't enough neurons to come up with a solution, it means you don't have enough experience. But that doesn't mean you have to memorise every task, you don't have to. You just have to solve a lot of problems and memorise the patterns themselves. So if a person was experienced, had enough neurons to solve this problem, then he is fit for the job. If he could not solve this problem, it means that he has not solved similar ones, it means that he does not have a general knowledge of patterns in this area.
@votanlean
@votanlean 8 ай бұрын
Then grind more 😂
@michaelc8638
@michaelc8638 7 ай бұрын
@@AndreiSokolov-k7j dude shut up. you would never solve this in 45mins having never seen it before. foh
@wassafshahzad8618
@wassafshahzad8618 7 ай бұрын
@@AndreiSokolov-k7j A yes cause obviously having experience in the technologies used in the real problems is less important then grinding leetcode. Yeah he is right no one is coming up with this solution if he hasn't seen this problem before hand
@nomad_1997
@nomad_1997 7 ай бұрын
You're either a genius, or you memorize it. Pick and choose. That's what I've learned grinding LC for the last two months.
@AlokRatnaparkhi
@AlokRatnaparkhi Жыл бұрын
For those who are wondering about -2 on the Line 13, for more readability you can rewrite this as : int partitionY = half - (partitionX + 1) - 1; //PartitionX is 0 indexed so you need to add 1 to exactly know the size of partition 1. Then you subtract it from half to know the size of partition B. Once you do that extra -1 at the end because we want to calculate index of partitionY. Partition should be 0 indexed as we are dealing with arrays. Even if you calculate this, you get half - partitionX - 2 in the end.
@amitbansal7754
@amitbansal7754 Жыл бұрын
Thanks. I was looking for this explanation
@LavanVivekanandasarma
@LavanVivekanandasarma Жыл бұрын
Ahh that makes sense ty!
@m_elhosseiny
@m_elhosseiny Жыл бұрын
Thanks champ!
@trsdesrn5246
@trsdesrn5246 Жыл бұрын
this is well explained!
@DevanshGoyal..
@DevanshGoyal.. 9 ай бұрын
I used it by default in my code and I was shocked that he used it too because no one on youtube has used this strategy for solving this problem
@clintondannolfo714
@clintondannolfo714 2 жыл бұрын
I've asked candidates this question for years at a Big Co and never once had a candidate successfully answer using this approach (after many interviews). Only a few even attempted it (but it wouldn't pass tests due to errors) and afterwards if candidates suggested it I only talked about it briefly to see their understanding and suggested them to do an easier solution. I feel like if I ever was made to implement the binary search version of this during an interview I'd fail, it's not really intuitive at all and neither is it telling me if a candidate is good or bad. Plenty of good people won't be able to get this in an interview, the false negative rate will be astronomical.
@atreides4911
@atreides4911 Жыл бұрын
is there a reason why you were asking this problem if it was so bad at detecting positive signals? were you told to do it?
@clintondannolfo714
@clintondannolfo714 Жыл бұрын
@@atreides4911 because I wouldn't expect the fully optimal solution. It's used just as a point for discussing about the problem and working through it, and getting some kind of working code. That part is where you get the signal, the signal is not from the solution itself. For myself anyway.
@atreides4911
@atreides4911 Жыл бұрын
@@clintondannolfo714 I see, thank you, that's helpful!
@draganostojic6297
@draganostojic6297 Жыл бұрын
It's hard LC and these are rarely asked in interviews
@graceng9921
@graceng9921 7 ай бұрын
But i did :)
@binetlee2534
@binetlee2534 3 жыл бұрын
Love your style of explanation, I was familiar with the log nature of binary search, but I couldn't wrap my head around the logic of what elements to choose each time. Your drawing of the partitions in different colors made a lot of sense, so thank you!
@ankitasinha3727
@ankitasinha3727 Жыл бұрын
For people solving it in Java, replace line#12 with int i = Math.floorDiv(l+r, 2); As mentioned, Python integer division // behaves different than languages like C/C++ and many others. In Python, if you type -1//2 you get -1 whereas in other languages you'd get 0
@benpurcell591
@benpurcell591 4 ай бұрын
Yes! Was wondering what on earth I did wrong when this dawned on me. Python was made for this question
@JackTheSpades
@JackTheSpades Жыл бұрын
Important note for those trying to solve this in different languages. Pyhton integer division // behaves different than languages like C/C++ and many others. In Python, if you type -1//2 you get -1 whereas in other languages you'd get 0.
@PippyPappyPatterson
@PippyPappyPatterson Жыл бұрын
Yeah, `//` is the floor division operator, not integer division.
@crimsonghoul8983
@crimsonghoul8983 Жыл бұрын
You are a lifesaver, man. I was literally struggling to understand how it would work if the division keeps giving 0 instead of -1.
@nw3052
@nw3052 Жыл бұрын
Yeah it was bugging me a lot, thanks man
@ayannaskar9195
@ayannaskar9195 Жыл бұрын
Yea man you saved 3 hrs of my life.
@VinitRaj-ym4lm
@VinitRaj-ym4lm 10 ай бұрын
yeah, we can use this function in java "Math.floorDiv(i+j, 2);"
@Dhruvbala
@Dhruvbala Жыл бұрын
I wish you'd picked two example arrays where one wasn't contained within the other. Would have made things a bit more clear
@pranjal5451
@pranjal5451 3 ай бұрын
That's exactly what I said lol
@nathanwailes
@nathanwailes 2 ай бұрын
I think in that case the binary search would just continue until one of the pointers went all the way to the other side.
@pinakadhara7650
@pinakadhara7650 Жыл бұрын
Here's the intuition that helped me understand this. In this problem, we are searching for the "correct partition" in an array, such that, 1. Number of elements in the merged array is (m+n) // 2 2. All the elements in the left partition of both the arrays are lesser than or equal to all the elements in the right partition of both the arrays 3. If ALeft > BRight --- shrink the partition 4. If BLeft > ARight --- increase the partition How do we know we can apply Binary search? - We have a rule which can tell us if we should move to the right or to the left in the solution space Here binary search can be run on any of the arrays, but we choose to run on the smaller one as it's more efficient.
@m_elhosseiny
@m_elhosseiny Жыл бұрын
Thanks! Just a small note, can you give more difficult examples when running through the algorithm drawing? I feel it makes it validates your solution more rather than the ideal case which sometimes makes the viewer doubt wehter this would work with edge cases. for eg: you used 2 sorted arrays starting from 1 increasing by 1: [1,2,3..etc] with one smaller than the other in length. I would've loved a second example were you use another set of arrays.
@AndreiSokolov-k7j
@AndreiSokolov-k7j 8 ай бұрын
As far as I'm concerned he shows the direction in which to think, and there can be so many cases and that will make for a great video. I think it is better that the video is not too big and shows the main point of the problem
@Philgob
@Philgob 3 ай бұрын
There's too many edge cases for some problems. As a business, he has to stay in that sweet spot of video length from 10-25 minutes. You just have understand the algo yourself and write out the edge cases you want if you're not conviced
@lostdollars9945
@lostdollars9945 2 жыл бұрын
i really really appreciate how you humbly admit when a problem is hard even for you it gives so me much relief that ok maybe i'm not exceptionally stupid if a guy from google thinks it's a tough problem
@ianokay
@ianokay Жыл бұрын
I wish he elaborated on 17:03 where he states "Now any of these indices could technically be out of bounds", because it seems odd in a binary search for the middle to be OOB, but I get that his while loop is not doing "while l
@EE12345
@EE12345 9 ай бұрын
The code actually fails if you do L R and the middle index becomes negative... but he didn't explain why exactly we need to do while True instead of L
@gna6614
@gna6614 3 ай бұрын
I think it is related to the cases of: 1) if nums1 = [1,2,3,4,5] and nums2 = [100,101] then doing binary search on nums2 (the smaller array) and doing the comparisons will keep bringing the right pointer to the left because the mid will be always greater than nums1[j + 1]. The opposite is true if nums1 = [1,2] and nums2 = [100,101,102], it will keep pushing the left pointer to the right and will go out of bound 2) the case mentioned at 13:07 where one of the arrays are empty, which also means it's the shorter one so the mid pointer will already be out of bounds from the beginning Also I think a better naming than Aleft, Aright can be partition_a1_end, partition_a2_start I'm not sure if i explained correctly or clearly. Hope someone else helps in clearing this up
@illu1na
@illu1na 16 күн бұрын
yeah i spent an hour trying to debug why my code isn't working after just seeing his concept video, and l
@yashjoon3889
@yashjoon3889 Жыл бұрын
If anyone coding this problem in c++ , remember that in python -1/2 gives -1 whereas in cpp -1/2 gives 0. So apart from coding the above code similarly in cpp add this check before assigning a value to i : int i; if(l+r < 0) i = -1; else i = (l+r)/2;
@zachlin7192
@zachlin7192 Жыл бұрын
thanks, just what im searching for!
@St1ggy
@St1ggy Жыл бұрын
Great point. In typescript, this works similarly. So, you should write: const i = Math.floor((l + r) / 2)
@huangrex299
@huangrex299 2 ай бұрын
Thanks for help me save time debuggins : )
@WaldoTheWombat
@WaldoTheWombat 2 жыл бұрын
When doing a regular binary search on a single array, we cut the array in half each time to zero in on the item we search for. The same principle is implemented here, both of the arrays are sorted, so it make sense to check the middle item of each of them each and then searching in the correct part instead of just iterating from start to finish.
@srinadhp
@srinadhp 3 жыл бұрын
your videos are like watching an engrossing edge of the seat thrillers.. The way you uncover the solution and the clean code are unparallell. Thank you!
@sankalparora9374
@sankalparora9374 Жыл бұрын
Yeah... it really is!
@ax5344
@ax5344 3 жыл бұрын
whenever I tried to search for a problem and i saw your video--- although it is not on top---it feels like such a relief! Thank you, please do more!
@roman_mf
@roman_mf Жыл бұрын
Took me a couple of re-watches to finally get that 'click' to understand your way of thinking. Amazing solution as always. I would say it's less about binary search itself and more about the logical thinking: we don't care about how the array will be partitioned, but we do care about rightmost value of left partition and leftmost value of the right partition. Knowing these values we can easily figure out the median value. Just brilliant. No way I would have ever came up to this solution by myself, let alone come up with this solution during the interview!
@tlz124
@tlz124 5 ай бұрын
Only a couple re-watches? You're super smart
@lovuitchen9332
@lovuitchen9332 3 жыл бұрын
Enjoy your videos, high quality and pythonic. Thank you! Just one note, it seems a "mistake" during explanation, at around 12:26-13:00, where it should be max(3,3)+min(4,4)/2, right? Because you wanna upper bound for the left arrays and lower bound for the right array, I believe.(which is correct in the code later actually--around 20:29)
@toekneema
@toekneema 3 жыл бұрын
Thanks, I thought nobody else noticed
@SreenathV
@SreenathV 3 жыл бұрын
(max(3,3)+min(4,4))/2
@rohitkumaram
@rohitkumaram 3 жыл бұрын
@@toekneema I also noticed , but during my second watch.
@xuxiangyu7025
@xuxiangyu7025 2 жыл бұрын
@@toekneema I noticed
@vishakarudhra8665
@vishakarudhra8665 2 жыл бұрын
I was totally searching for this comment. This should logically be the correct method for computing the median. The like from neetcode also confirms it, so that's a relief.
@georgeshaoyundong4590
@georgeshaoyundong4590 2 жыл бұрын
In c++, you have to use floor((l + r) / 2.0), otherwise you will not pass [1,3][2] test
@ogdenmills9666
@ogdenmills9666 2 жыл бұрын
yep, python // is specifically floor division. That caught me off guard when translating this solution to another language.
@optimusprime5040
@optimusprime5040 2 жыл бұрын
Thanks, been scratching my head on it for an hour.
@sarthaksuper284
@sarthaksuper284 2 жыл бұрын
Thnx man
@codefast93
@codefast93 Ай бұрын
Perfect explanation! Thanks for putting in the time. One thing, at 12:51, you wrote (min(3,3) + max(4,4))/2 but it should be (max(3,3) + min(4,4))/2 to find the correct median. You write it correctly later in the code.
@yuansyunyeh301
@yuansyunyeh301 2 жыл бұрын
I would like to suggest the 12 lines of codes may be modified for readable (15:32): i = (l + r) // 2 if (l < r) else -1 Because Python runs the codes doesn't expect the same with other languages. Thank you were sharing
@Dhanushh
@Dhanushh Жыл бұрын
Thank you so much. Busting my head for long time, why my Java equivalent isn't working. But can you explain how Python works without this change?
@bryce.ferenczi
@bryce.ferenczi Жыл бұрын
​@@Dhanushh python rounds to -inf rather than zero, so -1 // 2 = -1 in python, whereas C++ -1 / 2 = 0
@Slink1
@Slink1 Жыл бұрын
After watching this too many times to count, I finally understand some of the issues I have been having such as understanding how partitionY’s index is determined. You have no idea how impactful your videos are! Thanks so much ❤
@anujsinha6467
@anujsinha6467 2 жыл бұрын
Hats off man, I didn't felt confused for a single moment with formula or any this else, just dry ran the whole cases and every thing makes sense. Thankyou!
@djslimcodes2337
@djslimcodes2337 10 ай бұрын
If you are familiar with Ultimate Binary Search, then using a lower bound to find the first right element from nums1, which is bigger or equal to the corresponding 'remaining' left element from nums2, might be easier: var findMedianSortedArrays = function(nums1, nums2) { if (nums1.length > nums2.length) { [nums1, nums2] = [nums2, nums1]; } const totalLength = nums1.length + nums2.length; const halfLength = Math.floor((totalLength + 1) / 2); let left = 0; let right = nums1.length; while (left < right) { const mid1 = Math.floor((left + right) / 2); const mid2 = halfLength - mid1; if (nums1[mid1] >= nums2[mid2 - 1]) { right = mid1; } else { left = mid1 + 1; } } const mid1 = left; const mid2 = halfLength - mid1; let maxLeft, minRight; const LB1 = mid1 -1 const LB2 = mid2 - 1 const RB1 = mid1 const RB2 = mid2 if (LB1 < 0) { maxLeft = nums2[LB2]; } else if (LB2 < 0) { maxLeft = nums1[LB1]; } else { maxLeft = Math.max(nums1[LB1], nums2[LB2]); } if (RB1 === nums1.length) { minRight = nums2[RB2]; } else if (RB2 === nums2.length) { minRight = nums1[RB1]; } else { minRight = Math.min(nums1[RB1], nums2[RB2]); }; if (totalLength % 2 === 0) { return (maxLeft + minRight) / 2; } else { return maxLeft; } };
@vdyb745
@vdyb745 2 жыл бұрын
This is such a doozy problem !!! You have made my day with your clear cut explanation. I actually am understanding things which I thought I was too stupid to get !
@tomonkysinatree
@tomonkysinatree 5 ай бұрын
The way you write the solution out in code, it seems simple, but I am almost certain the edge cases with this approach would have totally stumped me if I get this in an interview
@shinoharakenshin7496
@shinoharakenshin7496 10 ай бұрын
Just in case anyone else is stuck on trying to replicate NeetCode's code solution, for line #12 "i = (l + r) // 2" my replicated code was not able to pass submission but I managed to get all tests passed after I changed it to "i = (l + r) // 2 + l", the addition of l allowed me to properly use i as an array index to obtain the end of the first partition, without adding l its index would be offset from start of the entire array instead of from the actual starting position as marked by the l pointer. I also added the line "if (r-l < 0) i = -1;" under #12 to pass some edge cases. I don't know if this discrepancy is caused by misunderstanding on my part or if there was a mistake in the video, so I'm putting it up here if anyone knows.
@TheGoya
@TheGoya 3 жыл бұрын
The part that's tricky to understand is where you increase/decrease the partition by 1, and why that doesn't lead to a degenerate linear case.
@yejimmy3533
@yejimmy3533 2 жыл бұрын
yeah I also got the same question.. why this operation would not lead the time complexity to O(N/2) as only half the length at inital stage
@tacticisacting3702
@tacticisacting3702 2 жыл бұрын
that's not the partition being decreased by one, you have l and r values and i is in the middle of them, by setting r to i -1 or l to i+1 you halve the distance between l and r at each step so you get logarithmic runtime
@gunking1949
@gunking1949 2 жыл бұрын
tbh the best part of the code is switching to process the shorter array between nums1 and nums2 otherwise there is a lot of headaches when you move the pointer in an array that is much larger than the other
@nathanwailes
@nathanwailes 2 ай бұрын
Here's my attempt at writing up what I think the logic is, just in case anyone else finds it helpful: 1. Our task is to find the median of the merged arrays, but do it in O(log(m+n)) time, suggesting a binary search approach. So what would we be doing a binary search of, and what would be the condition that would determine how to update the search and eventually end it? 2. We should notice that if the two arrays were merged, the median would be defined as the point where a left partition and right partition meet. So if there was some fast way to calculate where that partition happens in each constituent array (i.e. where each constituent array is divided into those elements that would be in the left partition in the merged array and which would be in the right partition), then we could find the median element in the required amount of time. 3. What we're going to do is do a binary search in the second array to find that partition point, thereby also finding the partition point in the first array (as I'll explain). We are going to compare the potential candidate values we identify in the second array to the first array to find the indices where each constituent array is divided into the segments that will go into the left and right partition in the merged array. 4. We start the binary search at the leftmost and rightmost indices of the second array as in a normal binary search. We take the middle of those, and that is our potential match that we want to consider (i.e. it's potentially the partition point in the second array). 5. A crucial insight is that by identifying that index in the second array, we also thereby know what the corresponding index must be in the first array, because the total length of those two left partitions in the constituent arrays must add up to the length of the left partition in the merged array. 6. A very difficult part of the problem is the comparison that then needs to happen to know if we've found the correct indices or not. We know if we've found the right indices if the end of the left partition in each constituent array is less than or equal to the beginning of the right partition in the other constituent array. 7. The other hard part is knowing which way to direct the binary search depending on the comparison of the two partition points. If the second array's partition point is too far to the left (the value is too small compared to the first array), we need to look to the right (set the left pointer equal to middle+1). The partition point is too far to the left if the first constituent array's left partition's last element is bigger than the second constituent array's right partition's first element.
@MikhailVainarevich
@MikhailVainarevich Жыл бұрын
Thank you for explanation, it is really great for understanding the logic. One thing I'm struggling to understand is why this method is O(log(n+m)). When the condition is not met, we increment the 1st half of smaller array by 1 and check again. In the worst case, we are going to do it n/2 times. Isn't it O(N) time complexity?
@slavaplek9875
@slavaplek9875 Жыл бұрын
I have exactly the same question
@pinakadhara7650
@pinakadhara7650 Жыл бұрын
We aren't actually "incrementing by 1" but moving the left pointer to "mid + 1". If you consider the smaller array's length as 11, mid = (0 + 11) // 2 = 5. If the condition doesn't match in this iteration, we move the "left pointer" to 6. Now mid = (6+11) // 2 = 8 I am not able to understand the why we are doing this though.
@fangzhongli9366
@fangzhongli9366 9 ай бұрын
I think this algorithm can also be applied to "k closest elements in a sorted array". After we find the closest index, we "partition" the array into 2 sorted halves. One half = target. And we can search for the range of the k closest elements with the method used here
@lianghe1401
@lianghe1401 5 ай бұрын
This is the best explanation (including the official leecode explanation) I could find. 1. The most thing I hate about binary search is to set the ending condition, such as while l
@eshanpandey4186
@eshanpandey4186 9 ай бұрын
This is the first time Nav I felt that the explanation was not up to the mark, the explanation for why infinity and -infinity could've been better, along with a reason for Binary Search on one array will be sufficient, that too why on the smaller one only!
@yitongxie6574
@yitongxie6574 2 жыл бұрын
Thx for the infinity trick. Couldn't come up with it. I really scratched my head trying to solve the edge cases
@moveonvillain1080
@moveonvillain1080 Жыл бұрын
Very important note: If you are trying to write the same logic in a different language keep in mind that Python's ' n//m ' does floor division meanwhile in languages like JAVA, C++ n/2 is Integer divison. So make sure to use a floor function on (l+r)/2. For JAVA int i = (int)Math.floor((l+r)/2.0); basically we find the double value of the division then it's floor and then convert it to int as the Math.floor() returns the value in double. This had me pulling my hair for an hour.
@tchovosky
@tchovosky 3 жыл бұрын
Love your answer, best I have seen so far. There are many others using recursion which make it really hard to understand. Yours is a variation of standard while loop with left/right pointers binary search. And it's much easier to code this way.
@BarryBecker4
@BarryBecker4 2 жыл бұрын
The only problem is that it is not actually O(lg(n)). See comments above.
@scottk3292
@scottk3292 Жыл бұрын
An edge case which I had expected to fail actually works correctly because the 'integer' (actually floor, not integer) division operator surprised me. With the shorter array having all values greater than the longer array, you end up with an i value of -1. I had expected -1 // 2 to be zero, rounding toward the origin, producing a wrong j index for the median, but I was wrong. The // operator always rounds down, even when dealing with negative results. In this case, -1//2 produces -1, so my fringe case still works perfectly.
@ilona7051
@ilona7051 Жыл бұрын
I think you could just as well write 'r = i + 1' in line 30 instead of 'l = i + 1' (since the only time l appears in the while loop is in line 12: i = (l + r) //2 ). I think it makes more sense to increment the right pointer by 1 than to touch the left pointer.
@world11191
@world11191 Жыл бұрын
I comprehended about 80% of that so thank you! I'll rest my brain, probably rewatch, and hope for a 100% tomorrow.
@harshitsangwan890
@harshitsangwan890 2 жыл бұрын
C++ Code for the same - Note that you need to use i = floor((lo+hi)/2.0) because we want -0.5/2 to evaluate as -1 and not 0. class Solution { public: double findMedianSortedArrays(vector& nums1, vector& nums2) { int n = nums1.size(), m = nums2.size(); if(m=0 ? nums1[i] : -INFINITY; r1 = i+1=0 ? nums2[j] : -INFINITY; r2 = j+1
@ninebysixteen222
@ninebysixteen222 Жыл бұрын
thank you so much man!! I have struggled for like 1 and half hour for this.thanks once again!!
@AlexanderVishnevskiy-t5v
@AlexanderVishnevskiy-t5v 2 жыл бұрын
I tried a similar approach but it was much harder). Initially, I searched for the middle index in the first array and then binary search on the second array. Time complexity O(logNlogM). I didn't know how to improve until I found this one. This solution is genius. Well done!
@whatislove4044
@whatislove4044 2 жыл бұрын
there is a mistake, you should start with l, r = -1, len(a) the code is invalid for this case [1,3] [2]
@qixuanli4369
@qixuanli4369 2 жыл бұрын
Yeah. I run into a Time Limit Exceeded when the input was [3] [-2,-1] Your fix worked. Thanks!
@kumaranp8764
@kumaranp8764 2 жыл бұрын
You are a life saver bruh
@Syed-wj4pj
@Syed-wj4pj 2 жыл бұрын
can anyone explain why is that the case?
@maratukhutdinov403
@maratukhutdinov403 2 жыл бұрын
Your comment was useful, but there is no mistake in his code:) He has "while True" loop, but I had a condition "while start
@JamesBond-mq7pd
@JamesBond-mq7pd 6 ай бұрын
For those who are wondering about -2 on the Line 13, for more readability you can rewrite this as : POSITION_B_LEFT = (HALF - 1) - (POSITION_A + 1) HALF - 1 cuz index starts from 0 POSITION_A + 1 cuz index starts from 0
@yuurishibuya4797
@yuurishibuya4797 Жыл бұрын
If ppl have not solved this before, it’s very unlikely that they can think of an optimum solution in the interview and code it covering all corner cases under 40+ minutes. Remember candidates have questions about team, work culture, etc as well to ask. I don’t know what knowledge about the candidate the interviewers will gain by asking these kind of questions. I have conducted a few hundred interviews, most of my questions tend to focus around what is expected to be known to work in my team from day one.
@TypicalRussianGuy
@TypicalRussianGuy Жыл бұрын
Hello, what your questions tend to contain? Asking to write a solution to a typical work-related issue? Please explain if possible. Also, by the way, these interview questions are not really designed to test a candidate. They are mostly designed to make it as hard as possible for a candiate so that a company could deny as many candidates as quickly as possible. It's kinda cruel, but it's one of the only ways companies like Google and Amazon can deal with the huge influx of people applying for a position.
@darshanvanza3889
@darshanvanza3889 Жыл бұрын
Hello Neetcoder, I have a request, Could you please make a video on leetcode problem number 2387 (Median of a row wise sorted matrix). It would be helpful. By the way, your content is amazing and keep up doing this great work. Thank you for all of the efforts you made from all of the neetcode family members.
@sarfrazahmad2580
@sarfrazahmad2580 8 ай бұрын
I tried doing it by eliminating values that can not be median by running binary search on both arrays. So at every iteration for both arrays you will get 2 inequalities which will tell max numbers of elemnts towards one side of the current value and get the min for the other. all values where min is greater than the max of the other (greater than 1 for even) will be eliminated (almost half the elements will get eliminated in each iteration)
@pepelepew4400
@pepelepew4400 3 жыл бұрын
Thank you for explaining the core concepts of the algorithm - this was super helpful
@thelookofdisapproval8234
@thelookofdisapproval8234 3 жыл бұрын
Thank you, this problem was bane of my existence for a long time
@symbol767
@symbol767 2 жыл бұрын
I swear, if an interviewer asked me for the binary search method of this problem I'd be tempted to slap them. The binary search method is beyond unintuitive, like if you never seen this problem, it is very very very unlikely you would come up with this on your own, especially in 45min
@sergeychepurnov1328
@sergeychepurnov1328 3 жыл бұрын
Thanks for an explanation. Java code is: public double findMedianSortedArrays(int[] nums1, int[] nums2) { int[] a = nums1; int[] b = nums2; //A must be shorter then B if (a.length > b.length) { a = nums2; b = nums1; } int total = a.length + b.length; int half = total / 2; int l = 0, r = a.length-1; double mid = 0.0; while (true) { int i = Math.floorDiv(l+r, 2); int j = half - i - 2; int Aleft = i >= 0 ? a[i] : Integer.MIN_VALUE; int Aright = i+1 < a.length ? a[i+1] : Integer.MAX_VALUE; int Bleft = j >= 0 ? b[j] : Integer.MIN_VALUE; int Bright = j+1 < b.length ? b[j+1] : Integer.MAX_VALUE; if (Bleft
@vandetpin4288
@vandetpin4288 2 жыл бұрын
This line is a must Math.floorDiv. Without it the program will not run
@neeldesai108
@neeldesai108 2 жыл бұрын
@@vandetpin4288 Yes. I faced the same issue. But why it is a must? Why can't we just perform normal division operation?
@Walery1k993
@Walery1k993 2 жыл бұрын
@@neeldesai108 Loot at the comment above Math.floorDiv() method in JDK, there is everything explained
@ianokay
@ianokay Жыл бұрын
It's an extremely unintuitive system using a binary search to try to randomly shift around the first partition until it isn't clearly incorrect. It's strange to even START with the premise "Okay so our left (merged) half is the left half of the smallest sorted plus the first rest of the longest sorted", and work from that, as it makes no sense why that would even work, and obviously if the smaller one is all larger numbers, it illustrates the nonsense, but the algorithm eventually works it out. It's just a strange pattern of thought since it starts with a premise that is immediately clear in making no sense and being incorrect, and then thrash around (semi efficiently) until a sensical correct solution pops out. What is weirdly unmentioned in this video is just the clarifying statement "What we're going to do is see how much of the smaller array we can use in the first half, by making the wildly incorrect assumption that it's the first half of it" (and it could be added "and correct our (almost certain) failure by moving logN instead of N+1, where we might actually over-shoot the actual correct portion, on behalf of a reduced complexity for large sizes of N")
@vitzal3691
@vitzal3691 Ай бұрын
For the wildly incorrect assumption, if the smaller array cannot be used in the left partition, the algorithm won't use it. That's the point of the binary search, it searches for the index of the smaller array to include into the left partition. When it doesn't include the small array in the left partition, the index (from the binary search) will be -1. This means, all the numbers in the left partition are those that are in the larger array (not necessarily all the numbers in the larger array). We won't overshoot the correct option on behalf of a reduced complexity for large sizes of N because the binary search will ensure that the left partition is constructed correctly by updating the bounds of that partition based on the maintaining the sorted order of the combined arrays.
@ianokay
@ianokay Ай бұрын
​@@vitzal3691 > "For the wildly incorrect assumption, if the smaller array cannot be used in the left partition, the algorithm won't use it." I'm aware, and I stated that it will course correct the incorrect assumption. What I'm pointing out however is just that the initial state, the assumption made when initializing the algorithm, is unintuitive because the premise (which I described) makes no sense... so I find it hard for a person to intuitively/naturally choose that initializing state for the solution. > "We won't overshoot the correct option on behalf of a reduced complexity for large sizes of N because the binary search will ensure that the left partition is constructed correctly by updating the bounds of that partition based on the maintaining the sorted order of the combined arrays." You WILL overshoot the correct option, because instead of course correcting the incorrect assumption N+1 (which you could, and would make sense), you jump ahead (thrash around) randomly logN, to reduce complexity for larger sizes of N (exactly as I said) Please read more carefully when/if contributing to the conversation
@konradhunter1407
@konradhunter1407 6 ай бұрын
I’ve been working on this problem for two days. 😖 My algorithm is a bit different but doesn’t work for the edge cases. Yours is much simpler and I’ll try it on my own now that I’ve seen it.
@Rahul-pr1zr
@Rahul-pr1zr 3 жыл бұрын
Nice explanation! One thing which wasn't clear to me was - why are we always choosing to do binary search on the smaller array? I'm guessing because it's faster but is there another reason for it?
@berkeevrensevdi1788
@berkeevrensevdi1788 2 жыл бұрын
I failed at input ([ ], [1]) when I chose bigger one. I think that when your merged array size is 1, you need to select nothing as left partition. But if you search bigger array, you actually start with selecting 1 as a left partition and it breaks the logic. So, you say that I am not going to choose any number for left partition but after that you select a number in bigger array for left partition. Also I failed at input ([1], [2, 3, 4, 5, 6]). Here, 3 numbers will be selected in left partition. When searching on bigger array, we initially choose [2,3,4] from bigger array and choose nothing from smaller array. So we compare bigger_left (which equals to 4) with smaller_right (which equals to 1). Since bigger_left is bigger than smaller_right, we need to narrow the partition of bigger array. When it is narrowed, we only select [2]. So, we need to select 2 numbers from smaller array but we are not able to do that since there is only 1 number in smaller array. I think that the amount of narrowing operation may exceed the size of smaller array.
@MsSkip60
@MsSkip60 3 жыл бұрын
Thanks for explanation, was asked this question this week and bollocks; it's too harsh for a phone interview despite it's not being a FAANG company!
@slimahmed5631
@slimahmed5631 4 ай бұрын
The solution that uses the 2 pointers approach is much more intuitive but i have to admit this way is more elegant & more creative
@mixtli1975
@mixtli1975 4 ай бұрын
More intuitive, but much slower. It's N time instead of log(N) since you have to check every element of the array instead of binary search.
@IntelliStar_
@IntelliStar_ Жыл бұрын
I used to hate this problem and kinda avoid solving it. But because of your clear explanation, I finally can solve it. Many thanks!
@ianokay
@ianokay Жыл бұрын
It's an extremely unintuitive system using a binary search to try to randomly shift around the first partition until it isn't clearly incorrect. It's strange to even START with the premise "Okay so our left (merged) half is the left half of the smallest sorted plus the first rest of the longest sorted, and work from that, as it makes no sense why that would even work, and obviously if the smaller one is all larger numbers, it illustrates the nonsense, but the algorithm eventually works it out. It's just a strange pattern of thought since it starts with a premise that is immediately clear in making no sense and being incorrect, and then thrash around (semi efficiently) until a sensical solution pops out.
@crazyfootball2271
@crazyfootball2271 9 ай бұрын
This code will miss oner edge case. The smaller array (A in this case) , what if we have completed the BS and element is not found yet. It can happen when median resides in B and all elements of A is larger than MEDIAN elements
@theghostwhowalk
@theghostwhowalk 2 жыл бұрын
Wow one of the toughest questions made look ridiculously simple. Lot of edge cases. Missing your videos past 2-3 months.
@kimmeyona8743
@kimmeyona8743 2 жыл бұрын
you need to set l, r = -1, len(a) and including when a is []
@Syed-wj4pj
@Syed-wj4pj 2 жыл бұрын
heyyyyy thankyouuu. this worked!!🏆
@OMFGallusernamesgone
@OMFGallusernamesgone 2 жыл бұрын
this question is crazy, how would you have known how to come up with O(log(m+n)) solution during an interview without having seen it before?
@NeetCode
@NeetCode 2 жыл бұрын
Hopefully the interviewer would give you a hint, because I doubt I could solve it first try 🙃
@TheNishant30
@TheNishant30 5 ай бұрын
i was able to do this by myself but it took an entire day of brainstorming.
@RaviChoudhary_iitkgp
@RaviChoudhary_iitkgp 2 жыл бұрын
in the code, where we are considering the case where either all the element of the half of combined sorted array could belong to one of the array, that case may result to i, j out of the bound and since we are assuming to always consider the smallest array to start with i.e array A, to consider that edge case we need to initialize l with -1 since the edge case for array A could be the case where all half belongs to array B and the value for r with len(A) which corresponds to the case where all the elements of A could be the part of the half of the array. Hence small correrction to the code on the part where we have initialized l = 0 and r = len(A)-1 the correct initialization would be l = -1 and r = len(A)
@benjacook3771
@benjacook3771 2 жыл бұрын
One way we can check this if that if we replace the while True with while l
@chaoluncai4300
@chaoluncai4300 2 жыл бұрын
this problem right here is avg by the 1st glimpse, but becomes harder n harder once I dig into those edge cases e.g. if ALeft @ index '0' ,BLeft index @ 'half-2', then if ALeft > BRight (@ 'half-1' ), means the 1st A element is invalid and shall be replace by BRight. Then new ALeft is @ '-1', while BRight is @ 'half", it's simple that ALeft(-inf) < BRight; on the other way BLeft (@'half-1') has to < Aright (@'0') is based on our previous observation from the last iteration (ALeft @ index '0'> BRight @ 'half-1' ). One last note for programmers not familiar with python, "//" is floor div, so -1 // 2 would produce -1 not 0. Hope this alleviates some anxieties for y'all, once again credits to NeetCode, he's so brilliant!!
@Saifkhan-jo3nx
@Saifkhan-jo3nx 3 ай бұрын
I did this, merged = sorted(nums1 + nums2) n = len(merged) if n % 2 == 0: return (merged[n // 2 - 1] + merged[n // 2]) / 2.0 else: return merged[n // 2] got the answer and came to see the video, and went like WHAT!!!!!!!!!!!!!!!
@Saifkhan-jo3nx
@Saifkhan-jo3nx 3 ай бұрын
this is not log(m+n), but nlog(n), but qualified.
@yash1311
@yash1311 2 жыл бұрын
Can somebody explain why r's values equates to len(A) - 1 instead or len(A) similarly why is the value of j equal to (half - i - 2) ? Any links to the explanation would also be helpful...
@anukritibanerjee
@anukritibanerjee 2 жыл бұрын
The reason for r's value len(A)-1 and not len(A) is because we considering the index. For a list A = [1, 2, 3], the index of 3 will be 2 i.e A[2] = 3 but len(A) = 3 which is out of bound since there is no value at A[3] and the reason for this behavior is because indexing starts at 0
@fadimichel1
@fadimichel1 2 жыл бұрын
Thank you so much, that was very helpful. But there is a small mistake in the explanation at 12:30, I am afraid that someone is confused: Max(3,3) + min (4,4), not the opposite.
@albertgao7256
@albertgao7256 3 жыл бұрын
For this puzzle, this is probably the clearest explanation online....
@fengliu975
@fengliu975 2 жыл бұрын
Still had to struggle bus for hours to get this but was able to attempt after watching first 2 min rather than having 0 idea like koko eats. These videos works man
@seuntaiwo8735
@seuntaiwo8735 2 жыл бұрын
Thank you very much for all your solutions. They are really helping me a lot with your clear-cut explanations. For this question, I'm wondering why we have to ensure var A holds the array with the lesser length. At first, I thought it was to ensure a smaller time complexity but I decided to test. I removed the code ensuring A was smaller and a test case failed. Can you please explain? Thanks❤
@Perrychen25
@Perrychen25 2 жыл бұрын
If you don't assign the A with the smaller one, then you may encounter the case: A: [2], B: [] half: 0, i = 0, j= 0 - 0 -2 = -2 which will lead to ALeft: 2, ARight: inf, BLeft: -inf, BRight: inf and return min(inf, inf)
@denysshushpanov7630
@denysshushpanov7630 Жыл бұрын
I solved this problem only thanks to your explanation, thank you very much
@surajpenugonda4756
@surajpenugonda4756 22 күн бұрын
why j = half-i-2 , you didnt said that while explaining
@218Flows
@218Flows 11 күн бұрын
Alright, I spent some time on this. Half is the length of half of the combined length of both arrays. It is a length not an index. We want to find the mid point of the second array based on half. What we have to do is convert the index i to a length, subtract it from half then convert that to an index. The key idea is converting the length to the index. If i convert i (any index) to a length i have to add 1.. If i convert a length to an index i have to subtract 1 to account for 0 based indexing. Now we want half minus the portion taken up by the midpoint of the first array half - (i + 1) --> basically convert i to a length and subtract it from half. There is one more step convert back to an index. final formula: half - (i + 1) - 1 which simplifies to half -i -1 -1 --> half - i - 2
@nobrainnogain7255
@nobrainnogain7255 Жыл бұрын
I guessed an idea in about 10mins. But it took almost 6 hours to implement it without bugs.
@blackcat_064
@blackcat_064 6 ай бұрын
Great walkthrough - I understood the solution really well in the end, except I literally wrote the same code as you (but in Java) and it kept getting stuck in infinite loops, when presented with arrays of length 1. I gave up cuz of this.
@paderborner5213
@paderborner5213 3 жыл бұрын
Can somebody please explain at what part the "binary search" is happening? In lines 28/30, the right/left index is de-/increased by 1. I'd expect some halfing of an interval at some point, if a binary search was performed.
@praveens5711
@praveens5711 2 жыл бұрын
We're decreasing/increasing the r and l pointers by subtracting or adding 1 to i and i is the value obtained by halving the interval at line number 12 :)
@kai75785
@kai75785 2 жыл бұрын
I fully agree with you. I believe this is worst case O(m), not O(log(min(m,n)). I see only 1 divide-by-2 and then a linear search. The "j = half - i - 2" is also just a guess which in his example works out perfectly but how about with (1, 2, 3, 4, 5) and (5, 6, 7, 8, 9)? You have to slide along about m/2 nodes - so it is O(m).
@KhavinKk
@KhavinKk Ай бұрын
One thing to note. For the operation -1//2, python will return -1. Cpp will return 0.
@davidlohmann5098
@davidlohmann5098 11 ай бұрын
Could the same technique be used to find the median of 3 or more arrays of length n1, n2, n3, ... in O(log(n1 + n2 + n3 + ...)) time?
@НинаКамкия
@НинаКамкия 25 күн бұрын
You are the best! Thanks u a lot! Gosh, your explanations are kinda some sorts of miracle
@omartahboub2900
@omartahboub2900 2 жыл бұрын
The Code explanation is NEET 😀👍👍👍👍👍!!!
@juliramoos
@juliramoos 11 ай бұрын
I think the problem was updated, right now it's definition says 0
@nehaa3778
@nehaa3778 2 жыл бұрын
Thanks for the approach and succinct but drilling explanation. I like how the videos don't unnecessarily drag on but are totally value laden.
@sauravus
@sauravus 2 жыл бұрын
Excellent! You're a LIFE SAVER
@likeXaXprodigy
@likeXaXprodigy 8 ай бұрын
There's one part of you code that is a bit confusing: As you note, we need to handle the case where there are no elements of A in the left partition. This would presumably corresponding to `l = -1`. However, you set up the boundary conditions such that the minimal value of `l = 0`. Your code ends up working correctly only because in these cases `r` goes beneath `l`. While this technically works, this generally isn't how you expect binary search to work, so looks like a mistake. I think it'd be clearer to set `l = -1` as your boundary condition.
@juliomedina5446
@juliomedina5446 2 жыл бұрын
I think you got Min and Max confused at @12:47 but other than that great video! Thanks for all your help
@sankalparora9374
@sankalparora9374 Жыл бұрын
By far the best explanation for Median of Sorted Arrays I ever got! Great job! Keep up!
@devdev19
@devdev19 2 жыл бұрын
Does anyone know why you have to run binary search on the smaller array? I've tested it on the larger array and it fails on some instances.
@Ahmedmeshref12
@Ahmedmeshref12 8 ай бұрын
Great explanation. I think your solution won't work aganist A = [1], B = [] as both of your rightA and rightB will be inf.
@brighttonyh
@brighttonyh 2 ай бұрын
Thank you for the video. The explanation is very intuitive. I do have one question, when actually implementing, what's the rationale of swapping array A and B (row 7 & 8 of the answer)? I wrote everything else the same but if I don't do the swap, it will fail at edge case when one of the array is empty. However I cannot think of why the core logic will fail if we don't sap
@benpurcell591
@benpurcell591 4 ай бұрын
For those using nc solution in c# and wondering why it isn't working as written here : in python -1/2 ==-1 in c# -1/2==0 Was wondering what was wrong for a while...
@weiqianzhang981
@weiqianzhang981 2 жыл бұрын
Fantastic video. Only one question. For this algo under the worst case, you actually need to move the pointer one by one till the end of an array and that may cause the time complexity to be O(m + n)? Because in order to get the log, isn't it necessary to move the pointer by half each time (not minus or add 1) so you can get the log part.
@Lucas-br6rt
@Lucas-br6rt 2 жыл бұрын
I was wondering the exact same thing
@mdazharuddin4684
@mdazharuddin4684 2 жыл бұрын
What do you mean? He is doing mid ± 1
@AkshayKumar-xh2ob
@AkshayKumar-xh2ob Жыл бұрын
Alert: java programmers. The output of p//q in python is different from p/q in java/cpp/c etc. So you will have to put a check while calculating mid that if (l + r) is negative, subtract 1 from mid.
@koeber99
@koeber99 Жыл бұрын
why is the out different?
@haoyuwang9784
@haoyuwang9784 Жыл бұрын
for java/cpp, define i in this way will work : int i = l > r ? -1 : (l + r) / 2;
@Allen-tu9eu
@Allen-tu9eu 3 жыл бұрын
the true god of leetcode problem teacher !
@NeetCode
@NeetCode 3 жыл бұрын
Thanks!
@aleksandrpokusaev9175
@aleksandrpokusaev9175 Жыл бұрын
I solved it using nlogn complexity much easier to understand. If you are using a binary search approach you have to use this trick and it is hard to memorize it.
@jamesmandla1192
@jamesmandla1192 Жыл бұрын
u can't use an alg with O(nlogn) in an interview. Actually, the bruteforce method in this problem is only O(n) where you merge both sorted arrays using two pointers and then get the middle index value. And that is still not good enough for most interviewers, so they definitely won't accept O(nlogn).
@hutlinh1830
@hutlinh1830 4 ай бұрын
@neetcode thanks for your great explanation. Which tool you are using for drawing example section?
@pooranik5342
@pooranik5342 9 ай бұрын
Very Clear Explanation.. Thank you so much
@DevanshGoyal..
@DevanshGoyal.. 9 ай бұрын
I think it will not work in this case when Array 1 is {1,3,5,7,9,10} and Array 2 is {4} here after failing one at mid value 5 of array1 high will be 3 and low will be 1 and because of this mid will point to 1 and that's why it would require 2 elements in array2 which are no there and so Bleft will be index 1 and there is o value at index 1 of array 2 as it's size is only 1 and as j>=0 it will accepted and Bleft will be b[1] which is not their and that's why this solution is wrong.
@jerrybao1934
@jerrybao1934 2 жыл бұрын
Thank you for the video! I do have one question: at around 17:24, you said that in an edge case, i could be out of bound as i
@oliverxie9210
@oliverxie9210 2 жыл бұрын
I have the same concern. I think `l` should start from -1 rather than 0. The algorithm never make the `l` variable decrease. So if the entire A array should go to the right part of the total array, there will be still at least one element(the A[0]) being put in the left part of the total array, which is wrong. The video is still very helpful though; I appreciate it a lot.
@abdullahjavid
@abdullahjavid 2 жыл бұрын
Think about the case where A = [] and B = [1]
@peanutbutter785
@peanutbutter785 2 жыл бұрын
This question is super hard for me. Thanks for the explanation!
@sakthisudarsen3617
@sakthisudarsen3617 14 күн бұрын
My runtime is 0ms, beats 100% , why shouldn't we use this? class Solution(object): def findMedianSortedArrays(self, nums1, nums2): nums3=nums1+nums2 arr=sorted(nums3) m=len(arr) if (m%2==0): return((arr[m//2-1]+arr[m//2])/2.0) else: return(float(arr[m//2]))
@OneMovies4You
@OneMovies4You 4 күн бұрын
Hey, buddy I am yash , i appreciate your solution, to be honest.i also thought that way but I got some bugs I am thanking you for solving those bugs , can we work with each other if u like
@nguyenhuukhiem5945
@nguyenhuukhiem5945 Ай бұрын
To clarify, the author made a typo at 12:45. It should be Max(3,3) and Min(4,4). Hope that helps you if you are confused.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 688 М.
How Much Tape To Stop A Lamborghini?
00:15
MrBeast
Рет қаралды 211 МЛН
快乐总是短暂的!😂 #搞笑夫妻 #爱美食爱生活 #搞笑达人
00:14
朱大帅and依美姐
Рет қаралды 12 МЛН
Ice Cream or Surprise Trip Around the World?
00:31
Hungry FAM
Рет қаралды 21 МЛН
Long Nails 💅🏻 #shorts
00:50
Mr DegrEE
Рет қаралды 14 МЛН
Search Insert Position - Binary Search - Leetcode 35 - Python
13:42
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 148 М.
Binary Search : Median of two sorted arrays of different sizes.
24:48
Tushar Roy - Coding Made Simple
Рет қаралды 549 М.
Trapping Rain Water - Google Interview Question - Leetcode 42
23:21
How Much Tape To Stop A Lamborghini?
00:15
MrBeast
Рет қаралды 211 МЛН