Trapping Rain Water - Google Interview Question - Leetcode 42

  Рет қаралды 393,173

NeetCode

NeetCode

Күн бұрын

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🐦 Twitter: / neetcode1
🥷 Discord: / discord
🐮 Support the channel: / neetcode
Coding Solutions: • Coding Interview Solut...
Dynamic Programming Playlist: • House Robber - Leetco...
Tree Playlist: • Invert Binary Tree - D...
Linked List Playlist: • Reverse Linked List - ...
Problem Link: neetcode.io/problems/trapping...
0:00 - Read the problem
5:40 - O(n) Memory Solution
11:00 - O(1) Memory Solution
20:05 - Coding Explanation
leetcode 42
This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
#pointer #array #python

Пікірлер: 325
@NeetCode
@NeetCode 2 жыл бұрын
🚀 neetcode.io/ - A better way to prepare for Coding Interviews
@nishantingle1438
@nishantingle1438 2 жыл бұрын
Why not create something like 350-450 also ? I think that is the minimum number of standard questions required to crack FAANG.
@fatorangecat21
@fatorangecat21 Жыл бұрын
@@nishantingle1438 do neetcode 150 and striver sde sheet along with some spicy extra questions you can find while browsing leetcode.
@sucraloss
@sucraloss Жыл бұрын
@@fatorangecat21 Didn't know about striver's thanks for the recommendation just added to my list
@lzosx
@lzosx 6 ай бұрын
honestly, it's not even the solution that make your videos so valuable; it's the fact that i get to take a look at your thought process which infinitely more assists in the structure of solving a problem
@DarnMyNameDoesntFi
@DarnMyNameDoesntFi 2 жыл бұрын
My favorite part about all of your videos is that you start out in a pretty chill vocal register and the moment you get to the crux of the problem you escalate and get super intense. I've been watching and trying to note when that always happens... it's pretty much the moment you start drawing out the problem. Anyone else notice this?
@goodgoodduckqi2139
@goodgoodduckqi2139 2 жыл бұрын
yes lmfao
@againnotgood8980
@againnotgood8980 2 жыл бұрын
thanks, apart from grasping leetcode 42, I also learned 3 more words: vocal register, crux, escalate
@MeridithLee
@MeridithLee 2 жыл бұрын
​@@againnotgood8980 lmao thank you for this, it made me laugh out loud in the middle of a leetcode grind
@knowledgedose1956
@knowledgedose1956 2 жыл бұрын
@@MeridithLee apparently I am not the only one who reads comments during leetcode video
@theastuteangler
@theastuteangler 2 жыл бұрын
@@againnotgood8980 crux is overrused, let this word die already
@prafulparashar9849
@prafulparashar9849 2 жыл бұрын
This explanation is so spot on that i actually coded everything myself before even looking into the code part of the video. You are doing great work !! Congrats on the new job and thanks a lot !!
@symbol767
@symbol767 2 жыл бұрын
I've come back to this problem so many times, I feel this is a horrid interview question, its beyond unintuitive. I guarantee 99% of the entry level dev's at least would not be able to figure out the solution to this problem if they've never seen the solution before. Even if they did 400 other leetcode problems
@thecap7249
@thecap7249 2 ай бұрын
It's kind of relaxing for me after reading this comment, I knew what needs to be done but was unable to put it in code.
@VV-ps8rt
@VV-ps8rt 7 күн бұрын
Lol same
@fatcat22able
@fatcat22able Жыл бұрын
For anyone confused about the res += leftMax - height[l] line like I was, look at the line above it. > leftMax = max(leftMax, height[l]) If leftMax is less than (or equal to) height[l], we set leftMax equal to height[l] and then subtract height[l] from it, which would equal zero. On the other hand, if leftMax is greater than height[l], we keep leftMax as is and subtract height[l] from it, which would be a positive value. In either case, the result will always be greater than or equal to zero, which means you don't have to check for negatives. Hope this helps!
@vamshisagargadde1629
@vamshisagargadde1629 Жыл бұрын
thanks, looking for this
@nw3052
@nw3052 Жыл бұрын
And if leftMax becomes greater than rightMax? That means we would add more water than the two pillars could hold since the minimum is the bottleneck. Honestly didn't quite get how his code worked.
@cagatay2462
@cagatay2462 Жыл бұрын
@@nw3052 if leftMax is greater, we start adding water from only right side. In other words, if leftMax is greater, we run else statement till while loop ends.
@nw3052
@nw3052 Жыл бұрын
@@cagatay2462 oh yeah, you're right. I got a bit of a tunnel vision in here.
@jasonahn8658
@jasonahn8658 10 ай бұрын
such a genius way to calculate it
@ThamaraiselvamT
@ThamaraiselvamT 2 жыл бұрын
you nailed it, I just solved my first ever hard problem at leetcode :D
@AshishKumar-dk5ve
@AshishKumar-dk5ve 3 жыл бұрын
Your way of explaining the problem and solution is simply AWESOME. Kudos to you !!!
@MP-ny3ep
@MP-ny3ep 2 жыл бұрын
This was a phenomenal explanation! You made it soooo easy. Thank you so much. You channel is gold. And , congrats for getting placed! I wish you all the success in the world!
@karthik829
@karthik829 2 жыл бұрын
Clear explanation !! I'm truly amazed how people can come up with this algorithm during and interview.
@andrewgordon4774
@andrewgordon4774 2 жыл бұрын
I’d say 95% of people don’t, you either get lucky and don’t get this question or have seen it before and know the technique
@prasad9012
@prasad9012 2 жыл бұрын
@@andrewgordon4774 Agreed. We just have to practice as many problems as we can to increase the probability of getting asked something we've already seen before.
@ShikaIE
@ShikaIE 2 жыл бұрын
@@prasad9012 agree. I think given the problem in day2day work, people might be able to work it out without the time limit and stress. It’s a bit ridiculous to think of it being the norm in the technical interview. But the good thing about it is that people who did this are at least aware and care about important of algorithms. Interviewers might consider those who came out with o(n) memory at least rather than the brute force.
@theastuteangler
@theastuteangler 2 жыл бұрын
this algorithm is easy
@geg_ant
@geg_ant 2 жыл бұрын
That is impressive how simple actual solution might be! Thank you!
@avahome5285
@avahome5285 3 жыл бұрын
the explanation is so natural. thank you.
@theornament
@theornament 5 ай бұрын
I was able to solve this by calculating the index of the greatest value and creating two loops where each one is designated for left and right pointers, and loop them until we reach the index where we found the greatest element. I basically calculated that we need to find the next greatest element in each loop (remembering that the next greatest value is current greatest value + 1) where, until it gets to that point, increase/decrease our pointers and sum the actual greatest value - the current value. The only difference for the right pointer loop is that we need to calculate if we already reached a point where we got to the greatest value (as it can be repeated). It's a bit more inefficient than this solution, but it's still O(n) so I'm proud of coming up with it myself.
@nikhildinesan5259
@nikhildinesan5259 3 жыл бұрын
Good to see you back after a long time !!!
@jacktrainer4387
@jacktrainer4387 2 жыл бұрын
Brilliant explanation. My loathing of this problem ran deep, until now.
@sabihabarlaskar8318
@sabihabarlaskar8318 2 жыл бұрын
Such a detailed explanation! Thank you!
@silkyjain5964
@silkyjain5964 2 жыл бұрын
You explained this so well. It was hard for me to understand this problem otherwise. Thank you!!
@andrewcenteno3462
@andrewcenteno3462 Жыл бұрын
The two pointer solution is insane, I would never come up with that 'on the spot' at an interview.
@idolgin776
@idolgin776 Жыл бұрын
Thanks for a great explanation! I am starting to play with algorithms, and this has been a big help.
@sarvesh6785
@sarvesh6785 Жыл бұрын
Your video is fantastic. Each video guarantees a precise and clear explanation.
@TarunKumar28
@TarunKumar28 2 жыл бұрын
Nicely explained, simple and elegant solutions.
@TheFatAssCat
@TheFatAssCat Жыл бұрын
Man some of these solutions seem so obvious after you see them. I brute forced this problem and while it took a while and worked, it was stupidly inefficient. And thus didn't pass Leetcode. Thank you for the excellent breakdown.
@TaiChiSWAG
@TaiChiSWAG 2 жыл бұрын
The way you start explaining makes the problem pretty easy 👍
@swagatzeher
@swagatzeher 3 жыл бұрын
So nicely explained ! Great job man
@karann6010
@karann6010 2 жыл бұрын
U make it look so easy ❤️ thanks a lot ☺️
@jobprep8136
@jobprep8136 11 ай бұрын
You are amazing mate !!!! I cant thankyou enough. Crisp, easy and efficient solutions.
@tanmoy003
@tanmoy003 2 жыл бұрын
One of the best explanation that I have seen!
@christendombaffler
@christendombaffler 10 ай бұрын
Goodness, this problem was hell for me to visualise. I gave up on it when doing it on my own after a couple of hours because I couldn't come up with anything and I couldn't understand any of the solutions and their explanations. In particular I really didn't understand how you didn't need O(n) to figure out the required filling in a given space even if we ignored one side or the other. I had to go through your position-by-position explanation twice and I needed to make an array for all 5 calculations just to understand how to process the idea correctly, but at least it's how I got my breakthrough, and figuring out the two pointer solution after that was trivial. Thank you for the video. Looking up what people thought were the hardest problems on leetcode and seeing this very problem get the most mentions made me feel a lot better about myself.
@jesuscruz8008
@jesuscruz8008 Жыл бұрын
great explanation like always! i wrote a long function to get this to work but your way was way better than mine glad i always watch your videos after im done to see a better way of doing the question
@mortal_coder4869
@mortal_coder4869 Жыл бұрын
this was amazing, proud of your videos NC, keep up the good work.
@praneshs8344
@praneshs8344 3 жыл бұрын
Thanks mate !! I really like your explanation, very understandable
@linli7049
@linli7049 3 жыл бұрын
I think we should use "while ( l < r - 1 )" instead of "while( l < r )" because we don't want to compute the water in the same position twice. So if l and r are adjacent, we should stop shifting l or r pointer. However, while ( l < r ) still works in leetcode. I am not sure if it is guaranteed to be correct if we use while ( l < r )
@twin392
@twin392 2 жыл бұрын
When L and R overlap, the leftMax and rightMax are going to be the true max, so doing rightMax or leftMax - height[l or r] always produces 0 and doesn't add to res. It's unnecessary but doesn't change the answer.
@anantprakashsingh8777
@anantprakashsingh8777 2 жыл бұрын
Well, when Left and Right pointer end up at the same position, they have also arrived at the highest value in the array. This would mean that no water can be trapped at that location, hence the answer would be correct regardless. Introducing your condition to the algorithm would result in one less comparison, that would result in a faster algorithm, but not by a significant margin. You can introduce your condition into the algorithm, the answer would still be correct.
@runeyman
@runeyman 2 жыл бұрын
Your explanation is so good that I'm able to implement the solution without seeing the code! 😁
@aashishbathe
@aashishbathe Жыл бұрын
Actual best, most efficient explanation!!
@tiennguyenthuy7563
@tiennguyenthuy7563 2 жыл бұрын
Very helpful. thank you. Keep up the inspiring work
@aiyifei4732
@aiyifei4732 2 жыл бұрын
Very neat solution! Thanks for the explanation.
@pinakadhara7650
@pinakadhara7650 Жыл бұрын
This is one crazy problem. Thanks for this great video!
@David-hs3fu
@David-hs3fu Жыл бұрын
Thanks!! This is the best presentation I've ever seen.
@nguyenbach4710
@nguyenbach4710 Жыл бұрын
the way u make prolems easier drive m crazy thanks a lot plz don't stop
@crosswalker45
@crosswalker45 2 жыл бұрын
amazing explantion..what an amazing brainstorming session
@svran1234
@svran1234 4 ай бұрын
This was so easy to understand and very neatly explained. Thank you so much!
@ralucaioan7609
@ralucaioan7609 Жыл бұрын
Thanks a lot, I love to learn from your videos!
@kirillzlobin7135
@kirillzlobin7135 8 ай бұрын
Thank you very much for such a great quakity of the material. You are doing an amazing job
@yazeed8240
@yazeed8240 6 ай бұрын
Really beautifully explained! Thanks for these videos!
@chayan_ghosh
@chayan_ghosh 6 ай бұрын
best explanation for this problem on yt. Thank you
@daniyalkabir6527
@daniyalkabir6527 2 жыл бұрын
Made it look so easy! Thanks for this.
@francaniilista
@francaniilista 6 ай бұрын
Thanks a ton, pal! Very clear explanation, I've tried to solve it, but I did not figure out alone before watching your video.
@daeyangcho9098
@daeyangcho9098 2 жыл бұрын
Really nice and cool explanation! Thanks very much!!!
@NeetCode
@NeetCode 2 жыл бұрын
Glad it helped!
@jackliu6351
@jackliu6351 3 ай бұрын
Your explaination of concept is so easy to understand!!!!!! keep making videos!!!!!
@vipulgoyal2370
@vipulgoyal2370 2 жыл бұрын
Awesome, Thanks for the intuition.
@fredtrentini6791
@fredtrentini6791 9 ай бұрын
Spent a bit more than 2 hours doing this one and some O(N ** 2) solution I came with ended up getting accepted. The whole time I was so worried about knowing where each of those gaps of water started and ended, until I looked for the best solution and noticed there was no need to know that, all I had to know was the maximum amount water that could be trapped in the current position. Great explanation.
@varanasiaditya
@varanasiaditya 2 жыл бұрын
This is just simply brilliant!
@hoyinli7462
@hoyinli7462 2 жыл бұрын
your explanation is the best!
@hassankazmi5443
@hassankazmi5443 Жыл бұрын
you make it so simple, great job
@yuchenzhang1741
@yuchenzhang1741 3 жыл бұрын
This is really helpful! Thanks!
@sankeerthsirikonda3565
@sankeerthsirikonda3565 2 жыл бұрын
Awesome explanation, BTW i think there is no need for if condition at the starting instead of returning 0, we will return res as 0 if there are no elements(while loop will not be executed)
@alexdeathway
@alexdeathway 13 күн бұрын
Since there is LeftMax and RightMax, it would cause an IndexError.
@sumeetkamat
@sumeetkamat 21 сағат бұрын
What an amazing explanation! It is supposed to be a HARD problem and you made it look so easy!
@avadhpatel111
@avadhpatel111 2 ай бұрын
Great explanation. Thank you very much for this video.
@matheusmenezes4702
@matheusmenezes4702 5 ай бұрын
Great solution! Thank you, brother!
@hoangvietng7100
@hoangvietng7100 3 ай бұрын
I have no words to say about how good your help is
@linli7049
@linli7049 3 жыл бұрын
Great explanation as always!
@TheRisingLlama
@TheRisingLlama 10 ай бұрын
Why is it l < r over l
@anujapuranik2000
@anujapuranik2000 9 ай бұрын
Thankyou again for this video.. you make all the videos so easy and your explanation skills are amazing!!! Thanks much:)
@80kg
@80kg 2 жыл бұрын
Thank you explained so clear!!
@kipa_chu
@kipa_chu 2 жыл бұрын
Thanks, excellent explanation.
@nanh2015
@nanh2015 2 жыл бұрын
very clever solution, thank you
@aduhaneh1057
@aduhaneh1057 Ай бұрын
i tried doing this question before going through the vid but couldn't figure it out. u r super smart man, thx for the thorough explanation
@ivantishchenko4686
@ivantishchenko4686 2 жыл бұрын
Superb explanation!
@user-vt2hi6hw9j
@user-vt2hi6hw9j Жыл бұрын
I really love your videos, please keep going on~
@royd-l
@royd-l Жыл бұрын
Great solution explained simply! Now the real question is how to be this clever in the actual interview
@raviyadav2552
@raviyadav2552 2 ай бұрын
this is super intuitive and easy thank you for the solution keep it up sir
@Haseebkhan-yd9ud
@Haseebkhan-yd9ud Жыл бұрын
after your explaination iactually coded it myseld love you bro
@deepanshugupta4901
@deepanshugupta4901 2 жыл бұрын
The Best explanation video on KZbin
@AbhinavKumar-ri8zi
@AbhinavKumar-ri8zi 2 жыл бұрын
watched atleast 10 videos on the same problem , yours explanation was the best and simplest . Thank you
@abhinavkumarr
@abhinavkumarr 2 жыл бұрын
i double this
@AbhinavKumar-ri8zi
@AbhinavKumar-ri8zi 2 жыл бұрын
@@abhinavkumarr damn another me !
@lakewobegonesbest8725
@lakewobegonesbest8725 11 ай бұрын
‘…and it’s actually pretty simple…’ Excuse me while I throw my laptop across the room.
@dorbie
@dorbie Жыл бұрын
I was once asked to code this but in 2D (really 3D considering it's a height field). It's an interesting challenge adding that extra dimension. I forget which company asked this (wasn't Google).
@bostonlights2749
@bostonlights2749 Жыл бұрын
was it samsung ?
@hoyinli7462
@hoyinli7462 2 жыл бұрын
you are fxxking genius in explaining concepts!! you got 1 new subscriber!
@mariamozgunova9584
@mariamozgunova9584 Жыл бұрын
It helped me realize the solution after 2 min of watching! Thank you!
@NeetCode
@NeetCode Жыл бұрын
I think you prob deserve more credit for that then me 🙂
@1mang0
@1mang0 2 жыл бұрын
thank u so much sir....ur videos are really helpful😄😄
@prempeacefulchannel
@prempeacefulchannel 2 жыл бұрын
Amazing explanation 👌
@Xeoncross
@Xeoncross Жыл бұрын
Instead of updating the maxLeft after you compare it, you can update it first so the subtraction will always be greater than or equal to 0. So you can always append the answer of "sum += leftMax - height[L]"
@HarshGupta-sl8ly
@HarshGupta-sl8ly 2 жыл бұрын
Very well explained !!!
@samarthtandale9121
@samarthtandale9121 Жыл бұрын
Great Explaination !!!
@shivkrishnajaiswal8394
@shivkrishnajaiswal8394 2 жыл бұрын
Underrated channel in Leetcode solution. Highly recommending this channel for Algo preparation
@weibinsun5771
@weibinsun5771 Жыл бұрын
Excellent! super helpful
@abhineykumar1773
@abhineykumar1773 Жыл бұрын
u are osm man, this kind of explanation wins my heart
@zourou228
@zourou228 4 ай бұрын
Great explanation!
@neelanshsharma275
@neelanshsharma275 4 ай бұрын
Did a few changes and was able to get 0ms runtime in Java :) Thanks NeetCode ❤
@user-ko7en6en1j
@user-ko7en6en1j Жыл бұрын
beautiful explanation. thanks
@eidiazcas
@eidiazcas 3 ай бұрын
I solved this using a stack for the heights on the left and calculating new volume while iterating the array, also O(N) solution, but I'd have never thought of the solutions you proposed here, very clever
@danielfirebanksquevedo891
@danielfirebanksquevedo891 2 жыл бұрын
Beautifully explained, thank you!
@KANISHKSAHUSIME
@KANISHKSAHUSIME 2 жыл бұрын
Thanks man very helpful
@user-cb1si7ig6p
@user-cb1si7ig6p Жыл бұрын
I don't even code in Python but I love your explanations, hence a subscriber.
@yamaan93
@yamaan93 9 ай бұрын
I know it doesn't end up mattering but a piece of feedback I thought I'd give on the video, the order in which you explain in the drawing is: 1. Move the pointer 2. Calculate Volume 3. Update the leftMax but in the actual code, you: 1. Move the pointer 2. update the max 3. Calculate the volume I understand that this doesn't end up mattering in the end, however it can make it really confusing if you can't figure out why that's fine.
@abhishekrbhat8919
@abhishekrbhat8919 Жыл бұрын
Beautiful explanation
@symbol767
@symbol767 2 жыл бұрын
Bro you are a king. Thank you.
@FitnessChaos
@FitnessChaos 3 жыл бұрын
Seems simple when you explain it but how do you come up with a solution when its all on the line? thats the frustrating part
@brandonnoll5527
@brandonnoll5527 3 жыл бұрын
Agreed. I'm just not so good at this stuff lmao.
@MrTacoMan123
@MrTacoMan123 2 жыл бұрын
right?? theres no way I could come up with this solution in < 25mins during interview if I havent seen this problem before
@akashkewar
@akashkewar 2 жыл бұрын
well, this is what it is all about. You solve problems that give you intuition and the same intuition can be used to solve multiple problems. The solution provided in the video is not the only solution, you can approach this problem in multiple ways from brute force to linear time and this is what would come to you automatically by solving problems.
@shubhamjaiswal1325
@shubhamjaiswal1325 Жыл бұрын
i am too dumb to come up with an optimal approach, unless I have sen such trick before
@sumitbanwakade9750
@sumitbanwakade9750 9 ай бұрын
Super Explaintion !!
@jingkaixie7898
@jingkaixie7898 2 жыл бұрын
Thank you!
LRU Cache - Twitch Interview Question - Leetcode 146
17:49
NeetCode
Рет қаралды 243 М.
I quit Amazon after two months
10:09
NeetCode
Рет қаралды 579 М.
WHO LAUGHS LAST LAUGHS BEST 😎 #comedy
00:18
HaHaWhat
Рет қаралды 19 МЛН
3M❤️ #thankyou #shorts
00:16
ウエスP -Mr Uekusa- Wes-P
Рет қаралды 14 МЛН
Big-O Notation - For Coding Interviews
20:38
NeetCode
Рет қаралды 426 М.
Container with Most Water - Leetcode 11 - Python
12:37
NeetCode
Рет қаралды 301 М.
Mastering Dynamic Programming - How to solve any interview problem (Part 1)
19:41
10 Math Concepts for Programmers
9:32
Fireship
Рет қаралды 1,8 МЛН
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 322 М.
Doing LeetCode Be Like (Coding Interviews Be Like Pt. 2)
4:41
Nicholas T.
Рет қаралды 748 М.
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Codebagel
Рет қаралды 129 М.
Trapping Rain Water - Leetcode 42 - 2 Pointers (Python)
9:51
Greg Hogg
Рет қаралды 2,4 М.
1$ vs 500$ ВИРТУАЛЬНАЯ РЕАЛЬНОСТЬ !
23:20
GoldenBurst
Рет қаралды 1,6 МЛН
ОБСЛУЖИЛИ САМЫЙ ГРЯЗНЫЙ ПК
1:00
VA-PC
Рет қаралды 1,7 МЛН
Опять съемные крышки в смартфонах? #cmf
0:50