Trapping Rain Water - Google Interview Question - Leetcode 42

Sdílet
Vložit
  • čas přidán 8. 07. 2024
  • 🚀 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
  • Věda a technologie

Komentáře • 323

  • @NeetCode
    @NeetCode  Před 2 lety +32

    🚀 neetcode.io/ - A better way to prepare for Coding Interviews

    • @nishantingle1438
      @nishantingle1438 Před 2 lety +3

      Why not create something like 350-450 also ? I think that is the minimum number of standard questions required to crack FAANG.

    • @fatorangecat21
      @fatorangecat21 Před rokem +1

      @@nishantingle1438 do neetcode 150 and striver sde sheet along with some spicy extra questions you can find while browsing leetcode.

    • @sucraloss
      @sucraloss Před rokem

      @@fatorangecat21 Didn't know about striver's thanks for the recommendation just added to my list

  • @lzosx
    @lzosx Před 6 měsíci +81

    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 Před 2 lety +478

    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 Před 2 lety +32

      yes lmfao

    • @againnotgood8980
      @againnotgood8980 Před 2 lety +76

      thanks, apart from grasping leetcode 42, I also learned 3 more words: vocal register, crux, escalate

    • @MeridithLee
      @MeridithLee Před 2 lety +5

      ​@@againnotgood8980 lmao thank you for this, it made me laugh out loud in the middle of a leetcode grind

    • @knowledgedose1956
      @knowledgedose1956 Před 2 lety +5

      @@MeridithLee apparently I am not the only one who reads comments during leetcode video

    • @theastuteangler
      @theastuteangler Před 2 lety +1

      @@againnotgood8980 crux is overrused, let this word die already

  • @prafulparashar9849
    @prafulparashar9849 Před 2 lety +117

    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 !!

  • @fatcat22able
    @fatcat22able Před rokem +109

    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 Před rokem +2

      thanks, looking for this

    • @nw3052
      @nw3052 Před rokem +1

      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 Před rokem +1

      @@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 Před rokem +1

      @@cagatay2462 oh yeah, you're right. I got a bit of a tunnel vision in here.

    • @jasonahn8658
      @jasonahn8658 Před 10 měsíci

      such a genius way to calculate it

  • @symbol767
    @symbol767 Před 2 lety +118

    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 Před 2 měsíci +7

      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 Před 4 dny

      Lol same

  • @MP-ny3ep
    @MP-ny3ep Před 2 lety +25

    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!

  • @AshishKumar-dk5ve
    @AshishKumar-dk5ve Před 3 lety +12

    Your way of explaining the problem and solution is simply AWESOME. Kudos to you !!!

  • @karthik829
    @karthik829 Před 2 lety +69

    Clear explanation !! I'm truly amazed how people can come up with this algorithm during and interview.

    • @andrewgordon4774
      @andrewgordon4774 Před 2 lety +79

      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 Před 2 lety +33

      @@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 Před 2 lety +15

      @@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 Před 2 lety

      this algorithm is easy

  • @geg_ant
    @geg_ant Před 2 lety +12

    That is impressive how simple actual solution might be! Thank you!

  • @theornament
    @theornament Před 5 měsíci +3

    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.

  • @ThamaraiselvamT
    @ThamaraiselvamT Před 2 lety +22

    you nailed it, I just solved my first ever hard problem at leetcode :D

  • @nikhildinesan5259
    @nikhildinesan5259 Před 3 lety +9

    Good to see you back after a long time !!!

  • @avahome5285
    @avahome5285 Před 3 lety +5

    the explanation is so natural. thank you.

  • @jacktrainer4387
    @jacktrainer4387 Před 2 lety +6

    Brilliant explanation. My loathing of this problem ran deep, until now.

  • @silkyjain5964
    @silkyjain5964 Před 2 lety +2

    You explained this so well. It was hard for me to understand this problem otherwise.
    Thank you!!

  • @sabihabarlaskar8318
    @sabihabarlaskar8318 Před 2 lety +5

    Such a detailed explanation! Thank you!

  • @sarvesh6785
    @sarvesh6785 Před rokem +3

    Your video is fantastic. Each video guarantees a precise and clear explanation.

  • @TaiChiSWAG
    @TaiChiSWAG Před 2 lety +1

    The way you start explaining makes the problem pretty easy 👍

  • @idolgin776
    @idolgin776 Před rokem +1

    Thanks for a great explanation! I am starting to play with algorithms, and this has been a big help.

  • @TarunKumar28
    @TarunKumar28 Před 2 lety +2

    Nicely explained, simple and elegant solutions.

  • @christendombaffler
    @christendombaffler Před 10 měsíci +1

    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.

  • @swagatzeher
    @swagatzeher Před 3 lety +2

    So nicely explained ! Great job man

  • @andrewcenteno3462
    @andrewcenteno3462 Před rokem +1

    The two pointer solution is insane, I would never come up with that 'on the spot' at an interview.

  • @karann6010
    @karann6010 Před 2 lety +4

    U make it look so easy ❤️ thanks a lot ☺️

  • @TheFatAssCat
    @TheFatAssCat Před rokem +3

    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.

  • @mortal_coder4869
    @mortal_coder4869 Před rokem

    this was amazing, proud of your videos NC, keep up the good work.

  • @linli7049
    @linli7049 Před 3 lety +5

    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 Před 2 lety +4

      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 Před 2 lety +3

      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.

  • @jobprep8136
    @jobprep8136 Před 11 měsíci

    You are amazing mate !!!! I cant thankyou enough. Crisp, easy and efficient solutions.

  • @tanmoy003
    @tanmoy003 Před 2 lety +3

    One of the best explanation that I have seen!

  • @TheRisingLlama
    @TheRisingLlama Před 10 měsíci +4

    Why is it l < r over l

  • @jesuscruz8008
    @jesuscruz8008 Před rokem

    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

  • @Xeoncross
    @Xeoncross Před rokem

    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]"

  • @runeyman
    @runeyman Před 2 lety +1

    Your explanation is so good that I'm able to implement the solution without seeing the code! 😁

  • @tiennguyenthuy7563
    @tiennguyenthuy7563 Před 2 lety +1

    Very helpful. thank you. Keep up the inspiring work

  • @praneshs8344
    @praneshs8344 Před 3 lety

    Thanks mate !! I really like your explanation, very understandable

  • @aashishbathe
    @aashishbathe Před rokem

    Actual best, most efficient explanation!!

  • @fredtrentini6791
    @fredtrentini6791 Před 9 měsíci +1

    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.

  • @shubhamjaiswal1325
    @shubhamjaiswal1325 Před rokem +2

    i am too dumb to come up with an optimal approach, unless I have sen such trick before

  • @ralucaioan7609
    @ralucaioan7609 Před rokem

    Thanks a lot, I love to learn from your videos!

  • @svran1234
    @svran1234 Před 4 měsíci

    This was so easy to understand and very neatly explained. Thank you so much!

  • @aiyifei4732
    @aiyifei4732 Před 2 lety

    Very neat solution! Thanks for the explanation.

  • @David-hs3fu
    @David-hs3fu Před rokem

    Thanks!! This is the best presentation I've ever seen.

  • @chayan_ghosh
    @chayan_ghosh Před 6 měsíci +1

    best explanation for this problem on yt. Thank you

  • @pinakadhara7650
    @pinakadhara7650 Před rokem

    This is one crazy problem. Thanks for this great video!

  • @nguyenbach4710
    @nguyenbach4710 Před rokem

    the way u make prolems easier drive m crazy thanks a lot plz don't stop

  • @yazeed8240
    @yazeed8240 Před 6 měsíci

    Really beautifully explained! Thanks for these videos!

  • @kirillzlobin7135
    @kirillzlobin7135 Před 8 měsíci

    Thank you very much for such a great quakity of the material. You are doing an amazing job

  • @daniyalkabir6527
    @daniyalkabir6527 Před 2 lety

    Made it look so easy! Thanks for this.

  • @sankeerthsirikonda3565
    @sankeerthsirikonda3565 Před 2 lety +6

    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 Před 10 dny

      Since there is LeftMax and RightMax, it would cause an IndexError.

  • @yuchenzhang1741
    @yuchenzhang1741 Před 3 lety

    This is really helpful! Thanks!

  • @vipulgoyal2370
    @vipulgoyal2370 Před 2 lety

    Awesome, Thanks for the intuition.

  • @aduhaneh1057
    @aduhaneh1057 Před měsícem

    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

  • @jackliu6351
    @jackliu6351 Před 3 měsíci

    Your explaination of concept is so easy to understand!!!!!! keep making videos!!!!!

  • @varanasiaditya
    @varanasiaditya Před 2 lety

    This is just simply brilliant!

  • @hassankazmi5443
    @hassankazmi5443 Před rokem

    you make it so simple, great job

  • @francaniilista
    @francaniilista Před 6 měsíci

    Thanks a ton, pal! Very clear explanation, I've tried to solve it, but I did not figure out alone before watching your video.

  • @FitnessChaos
    @FitnessChaos Před 3 lety +10

    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 Před 3 lety +2

      Agreed. I'm just not so good at this stuff lmao.

    • @MrTacoMan123
      @MrTacoMan123 Před 2 lety +7

      right?? theres no way I could come up with this solution in < 25mins during interview if I havent seen this problem before

    • @akashkewar
      @akashkewar Před 2 lety +1

      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.

  • @matheusmenezes4702
    @matheusmenezes4702 Před 5 měsíci

    Great solution! Thank you, brother!

  • @crosswalker45
    @crosswalker45 Před 2 lety +1

    amazing explantion..what an amazing brainstorming session

  • @dorbie
    @dorbie Před rokem +14

    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).

  • @royd-l
    @royd-l Před rokem

    Great solution explained simply! Now the real question is how to be this clever in the actual interview

  • @linli7049
    @linli7049 Před 3 lety

    Great explanation as always!

  • @user-vt2hi6hw9j
    @user-vt2hi6hw9j Před rokem

    I really love your videos, please keep going on~

  • @hoyinli7462
    @hoyinli7462 Před 2 lety

    your explanation is the best!

  • @80kg
    @80kg Před 2 lety

    Thank you explained so clear!!

  • @Haseebkhan-yd9ud
    @Haseebkhan-yd9ud Před rokem

    after your explaination iactually coded it myseld love you bro

  • @hoangvietng7100
    @hoangvietng7100 Před 2 měsíci

    I have no words to say about how good your help is

  • @avadhpatel111
    @avadhpatel111 Před 2 měsíci

    Great explanation. Thank you very much for this video.

  • @anujapuranik2000
    @anujapuranik2000 Před 8 měsíci

    Thankyou again for this video.. you make all the videos so easy and your explanation skills are amazing!!! Thanks much:)

  • @shivkrishnajaiswal8394
    @shivkrishnajaiswal8394 Před 2 lety +3

    Underrated channel in Leetcode solution. Highly recommending this channel for Algo preparation

  • @kipa_chu
    @kipa_chu Před 2 lety

    Thanks, excellent explanation.

  • @raviyadav2552
    @raviyadav2552 Před 2 měsíci

    this is super intuitive and easy thank you for the solution keep it up sir

  • @nanh2015
    @nanh2015 Před 2 lety

    very clever solution, thank you

  • @HarshGupta-sl8ly
    @HarshGupta-sl8ly Před 2 lety

    Very well explained !!!

  • @danielfirebanksquevedo891

    Beautifully explained, thank you!

  • @deepanshugupta4901
    @deepanshugupta4901 Před 2 lety

    The Best explanation video on CZcams

  • @hoyinli7462
    @hoyinli7462 Před 2 lety

    you are fxxking genius in explaining concepts!! you got 1 new subscriber!

  • @demaxl732
    @demaxl732 Před 9 měsíci

    This guy seriously just made a hard problem look so easy

  • @daeyangcho9098
    @daeyangcho9098 Před 2 lety +2

    Really nice and cool explanation! Thanks very much!!!

  • @samarthtandale9121
    @samarthtandale9121 Před rokem +1

    Great Explaination !!!

  • @yamaan93
    @yamaan93 Před 9 měsíci +1

    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.

  • @weibinsun5771
    @weibinsun5771 Před rokem

    Excellent! super helpful

  • @ivantishchenko4686
    @ivantishchenko4686 Před 2 lety +1

    Superb explanation!

  • @eidiazcas
    @eidiazcas Před 2 měsíci

    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

  • @symbol767
    @symbol767 Před 2 lety

    Bro you are a king. Thank you.

  • @KANISHKSAHUSIME
    @KANISHKSAHUSIME Před 2 lety

    Thanks man very helpful

  • @zourou228
    @zourou228 Před 4 měsíci

    Great explanation!

  • @user-cb1si7ig6p
    @user-cb1si7ig6p Před rokem

    I don't even code in Python but I love your explanations, hence a subscriber.

  • @tttrrrrr1841
    @tttrrrrr1841 Před 9 měsíci

    This is the first hard problem I have ever solved! Although I only got the O(n)/O(n) solution (I used linear extra space for the "left" side), not O(1) space. I knew it must be possible with two pointers since I did Container With Most Water, I just couldn't quite get the logic correct.

  • @sumitbanwakade9750
    @sumitbanwakade9750 Před 9 měsíci

    Super Explaintion !!

  • @neelanshsharma275
    @neelanshsharma275 Před 4 měsíci

    Did a few changes and was able to get 0ms runtime in Java :)
    Thanks NeetCode ❤

  • @abhineykumar1773
    @abhineykumar1773 Před rokem

    u are osm man, this kind of explanation wins my heart

  • @user-ko7en6en1j
    @user-ko7en6en1j Před rokem

    beautiful explanation. thanks

  • @MsSkip60
    @MsSkip60 Před 3 lety

    Thanks man!

  • @siyamafroz
    @siyamafroz Před 10 měsíci

    Bro you are a life saver.

  • @yuyingwu3313
    @yuyingwu3313 Před měsícem

    well explained, thanks :)

  • @prempeacefulchannel
    @prempeacefulchannel Před 2 lety

    Amazing explanation 👌

  • @abhishekrbhat8919
    @abhishekrbhat8919 Před rokem

    Beautiful explanation

  • @mingjiesong5042
    @mingjiesong5042 Před 2 lety +4

    Great explanation! One bug in the code: the l increment and r decrement should be after finishing recalculating the leftMax and rightMax instead of before.

    • @aravindmeyyappan8368
      @aravindmeyyappan8368 Před 2 lety +1

      No, at the start both maximumLeft and height[l] are same. So as the name maximumLeft suggests, it should hav value left of height[l].