Container with Most Water

Sdílet
Vložit
  • čas přidán 20. 10. 2018
  • For business inquiries email partnerships@k2.codes Container With Most Water LeetCode coding solution. One of Facebook's most commonly asked interview questions according to LeetCode.
    Coding Interviews Container With Most Water (LeetCode) question and explanation.
    This question is a commonly asked by the following companies: Facebook,Google, Microsoft, Airbnb, Goldman Sachs, Alibaba, and Adobe.
    Link to problem: leetcode.com/problems/contain...
    Problem description: Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
    Note: You may not slant the container and n is at least 2.
    Intuition behind solution: O(n^2) compare every possible 2 pairs of vertical lines and continually update the maximum area. Two pointer approach: continuously move two pointers (that start at the beginning and end of the array) toward each other. At each iteration, calculate the area (updating the max area if necessary) and move the increment or decrement the pointer that is pointing to the smaller vertical line.
    My Desk Setup
    Desk - bit.ly/3jfY195
    Chair - amzn.to/2O9TM3r
    Monitor - amzn.to/3rcSHGa
    Webcam - amzn.to/2NUmwgi
    Desktop - amzn.to/3tiySPL
    Laptops - amzn.to/3aRoN3Z
    iPad - amzn.to/2LlJzzJ
    Keyboard - amzn.to/3jfbxdd
    Mouse - amzn.to/36ElWtT
    Wrist Rest - amzn.to/3trrHF4 (pls don't buy this)
    Mouse Pad - amzn.to/2Myz2lt
    Microphone - amzn.to/3atNyTA
    Lamp - amzn.to/3jjfZYp
    Headphones - amzn.to/3tvr0KU (new model)
    Headphone Hook - amzn.to/3tr8uTC
    Blue Light Glasses - amzn.to/3cDVUdK
    Wireless Charger - amzn.to/39LY1uu
    Keyboard cable - amzn.to/2O5p2R5
    Mic arm - amzn.to/3cECZj8
    Audio interface - amzn.to/36HdWIi
    Cloudlifter - amzn.to/36VO6kf
    Laptop dock - amzn.to/2O2DsBw
    Motherboard - amzn.to/3rkiWuA
    Solid state - amzn.to/3rk5vuo
    CPU cooler - amzn.to/3tnwwPA
    CableMod - amzn.to/3tqbtM8
    CPU - amzn.to/3auG1ns
    Power supply - amzn.to/3trsAxo
    RAM - amzn.to/39JZcuf
    Designing Data-Intensive Applications - amzn.to/2YK4ek1
    Clean Code - amzn.to/3txqfB5
    Meditations - amzn.to/3cDa4fi
    Support me on Patreon: / kevinnaughtonjr
    Follow me on Twitter: / kevinnaughtonjr
    Follow me on Instagram: / programeme
    Follow me on GitHub: github.com/kdn251 Discord: bit.ly/K2-discord
  • Věda a technologie

Komentáře • 137

  • @KevinNaughtonJr
    @KevinNaughtonJr  Před 5 lety +254

    Do you guys prefer me going through 2 different solutions? I.e. the "naive" approach and the improved approach?

  • @priyankamalviya3613
    @priyankamalviya3613 Před 5 lety +30

    This is the most simplified explanation I came across! Thanks !

  • @wulymammoth
    @wulymammoth Před 5 lety +21

    I like that you went through the brute force version first.
    In the optimized example, the way I thought about it was moving the smaller wall in search of a bigger wall - keeping in mind that as we slide the smaller wall closer to the other wall we need an even higher wall to maintain our existing area or exceed it

  • @slavabit8020
    @slavabit8020 Před 4 lety +6

    Dude, this stuff is amazing. Not only easy to understand, but also gives me this cozy feeling of coding with my buddy. Subscribed

  • @sohbetdovranov1362
    @sohbetdovranov1362 Před 5 lety +7

    It's just awesome man. I couldn't understand the top rated solution on leetcode but yours is truly simple and well-explained. Best of luck!

  • @Uber_handle
    @Uber_handle Před 3 lety +3

    Follow-up with this, with trapping rain-water..similar approach a few nuances...love to hear your take!

  • @harinijeyaraman8789
    @harinijeyaraman8789 Před 4 lety +1

    You're doing a great job ! Love your videos ! Really good explanations

  • @mrdude1084
    @mrdude1084 Před 5 lety +15

    You made this tough problem look so simple... I really wanna reach your level of coding..

  • @giorgi23
    @giorgi23 Před 4 lety

    Thanks man for this explanation. First example doesn't work properly if your input is {1, 1} or {1, 2} but second example is just brilliant

  • @soumyasengupta7018
    @soumyasengupta7018 Před 5 lety

    This is one of the best problems on greedy approach.
    Nice video.

  • @loidforger6413
    @loidforger6413 Před 3 lety

    thank you, the way you explain when you code is really good

  • @AbhishekYadav-bw1mz
    @AbhishekYadav-bw1mz Před 4 lety +2

    You are doing god's work my friend.

  • @jayeshborgaonkar9166
    @jayeshborgaonkar9166 Před 4 lety

    you make it look so easy .. please keep doing the good work thanks

  • @nachiketlele9006
    @nachiketlele9006 Před 4 lety +1

    Wooo thanks!! Been at this quiet some time, this video cleared it up.

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 4 lety

      Nachiket Lele happy to hear it! If you need help with other problems and interview prep in general be sure to subscribe to the interviewing service I created, The Daily Byte! I recommend joining the annual plan thedailybyte.dev/

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

    I dont understand why most solutions dont consider the case when height[i] == height[j] more in detail. To me it doesn't make sense to jut decrement j when they are the same. Shouldn't there be another set of checker that will check in this case height[i+1] and height[j-1] and only choose the higher value one? Because when you decrement j, it could have been the case that it would have been better to increment i instead?

  • @galanoth17
    @galanoth17 Před rokem

    Yes i came up with this exact same optimal solution myself after thinking for 20 minutes. Woot woot.

  • @yakovkemer5062
    @yakovkemer5062 Před 2 lety

    Oh my God. Dude, you are amazing. It is the best explanation of algorithm I have ever seen. Subscription, like and all best wishes.

  • @kaushikramachandran
    @kaushikramachandran Před 4 lety +1

    Great explanation! Thanks. Just not getting one thing. How are we incrementing i, if heights[i]

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

    Heh, been solving leetcode for almost a month,this is the first one I got both of these solutions by myself,without any help. Big d.. energy!

  • @GaganBattoo
    @GaganBattoo Před 3 lety

    Hi Kevin... You did a great job.. just a suggestion though - two pointer approach can do this in O(n) time :)

  • @AyushSharma-ux4fk
    @AyushSharma-ux4fk Před 5 lety +3

    The moment I read the question, Kadane's algo just popped up into my head.

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

      I was just wondering how this problem is related to Kadane. Would you mind giving some more details?

  • @prathamj2215
    @prathamj2215 Před 3 lety +4

    What happens when height[i] and height[j] are equal? Which pointer (i or j) would you increment in that case?

    • @shivanib4723
      @shivanib4723 Před 3 lety +1

      According to the code else part executes so right pointer(j) decrements

    • @TheInuyashaGuy
      @TheInuyashaGuy Před 2 lety

      It also doesn't matter which one you change. Visualize a scenario where walls are of equal height. The ONLY way that you find a bigger container within those walls, is if there are two higher walls within the indices. If this is the case, then it doesn't matter whether you increment i or j, you will reach the solution either way.

  • @GauravKawatrakir
    @GauravKawatrakir Před 3 lety

    Why only smaller need to be move whether its from right or left side ??

  • @aj9706
    @aj9706 Před 4 lety

    Two pointer technique is used when array is sorted right??

  • @abishekkachroo938
    @abishekkachroo938 Před 4 lety

    Can someone please explain how j & i pointers are related to the heights ?

  • @sayantaniguha8519
    @sayantaniguha8519 Před 2 lety

    What is the difference b/w this Q and *Largest Rectangle in Histogram* ?

  • @harinathamasa9354
    @harinathamasa9354 Před 3 lety

    Yo! Awesome dude. Thank you!

  • @sandipbhaumik
    @sandipbhaumik Před 4 lety

    hi Kevin, Isn't be the minus of the heights at each index?

  • @1ashish01
    @1ashish01 Před 4 lety

    How does your bruteforce method pass the test case of continous incresing or descreasing numbers like suppose 1 2 3 4 5????.. answer should be 0 in this case and your approach will give 6 in this case.

  • @asishpanda3547
    @asishpanda3547 Před 2 lety

    amazing explanation

  • @sparkle060997
    @sparkle060997 Před 3 lety

    Why doesn't it matter what direction you move when both the left pointer and right pointer are the same height?

  • @ezdoesitnow
    @ezdoesitnow Před 2 lety

    F me, I got a time limit exceeded doing recursion. I didn't think that you could just do 2 pointers, it makes sense now that I see it

  • @Shiva_polishetty
    @Shiva_polishetty Před 3 lety +1

    bro, you don't mention the base case?

  • @swatidileep2060
    @swatidileep2060 Před 4 lety

    Is this question same as the Trapping rain water question?

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

    OMG, i saw this as very big, because the difficulty level is medium, so i viewed it as very big and i got the approach since its medium I spent an other 3 hours for nothing, and then saw the solution and realised i should go through question twice

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 5 lety +1

      Did you end up getting it? LMK if I can help with anything!

    • @saicharan8675
      @saicharan8675 Před 5 lety

      @@KevinNaughtonJr Yes i did.. Thank you soo much for your videos.. I'm naive to leet code.. please include basic(brute force) followed by best approaches in your videos like you did now

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 5 lety +1

      @@saicharan8675 Awesome happy to hear it! I'll try my best to do that sometimes it slips my mind! I actually just uploaded another video if you're interested in watching the latest one! czcams.com/video/cQX3yHS0cLo/video.html

    • @saicharan8675
      @saicharan8675 Před 5 lety

      @@KevinNaughtonJr Thank you i will go through it..

  • @subhedarsanchay
    @subhedarsanchay Před 4 lety +1

    I am not sure why this solution works when the height of the left and right are the same? How did we decide we can move only one side of container and hope to find the max area?

    • @byagnathavaasi
      @byagnathavaasi Před 4 lety

      the same doubt killing me..plz mention if anyone finds the answer....thanks in advance.

    • @ahmedfattah5879
      @ahmedfattah5879 Před 3 lety

      @@byagnathavaasi
      int fixConflict(vector& height,int s ,int e)
      {
      if(s>=e)
      return -1;
      int mymax=min(height[s],height[e])*(e-s);
      if(height[e]height[s]){
      mymax=max(mymax,fixConflict(height,++s,e));
      }
      else{
      mymax=max(fixConflict(height,++s,e),max(mymax,fixConflict(height,s,--e)));
      }
      return mymax;
      }
      int maxArea(vector& height) {
      return fixConflict(height,0,height.size()-1);
      }
      the basic idea that you will try recursively the both chances and get the maximum .

  • @rajathnayak5624
    @rajathnayak5624 Před 4 lety

    it would be a big help if you explain your approach on a whiteboard
    cause your solutions are just awesome

  • @chandrashekhardusari6966

    Awesome👏👏

  • @Hgh38
    @Hgh38 Před 3 lety +1

    When an if statement was the reason why your solution wasn’t passing all test cases

  • @andresalba34
    @andresalba34 Před 2 lety

    damn these leet questions are so freaking hard lol

  • @mohanreddy4669
    @mohanreddy4669 Před 5 lety

    Didn't understand why you were doing, min * (j - i) in the brute force solution. Could you please elaborate if possible?

    • @andrejmokris6127
      @andrejmokris6127 Před 4 lety +1

      Mohan reddy lower of heights (because water would otherwise leak :D) * distance between two indexes in array

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

    In the beginning, can we set max equal to 0?

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 5 lety +1

      I think that should be fine. I normally use something like Integer.MIN_VALUE so that the first time I calculate an area it's guaranteed to be larger and for error checking i.e. if at the end of the function if it's still equal to Integer.MIN_VALUE there's probably a problem.

  • @patricechaula3430
    @patricechaula3430 Před 2 lety

    In the second approach what if height[i] and height[j] are equal?

  • @wangwei83
    @wangwei83 Před 4 lety +1

    Why the second algorithm guaranteed to NOT missed the optimal solution?

    • @pyetwi
      @pyetwi Před 4 lety

      Because you know that the width of the cylinder is constantly decreasing. Thus, the only other possible way to obtain a higher volume would to obtain a greater height, which is essentially what the second algorithm aims to do.

  • @ranjeetkumar4069
    @ranjeetkumar4069 Před 3 lety

    🔥🔥🔥

  • @HolyHarmonyOfficial
    @HolyHarmonyOfficial Před 4 lety

    Hi Kevin, I have a question, why do we need have this step min*(j-i)? what's this useful?

    • @srinimurthy
      @srinimurthy Před 4 lety +1

      min * (j -1) is what gives you the volume. the span of columns between j(right) and i (left) and the height of water (m) is your volume

  • @nikhil.pandey
    @nikhil.pandey Před 4 lety

    can you please explain how you reach at this solution.......???

  • @vk1618
    @vk1618 Před 4 lety

    Optimizing for 2 parameters: decrease one only in pursuit of increasing other

  • @SolamanRaji
    @SolamanRaji Před 3 lety

    Thnx :) It was helpful.

  • @liutomzhi
    @liutomzhi Před 4 lety +3

    what if Height[i] and Height[j] is the same in the second option?

    • @liutomzhi
      @liutomzhi Před 4 lety

      I meant "are the same" :-)

    • @hacker-7214
      @hacker-7214 Před 4 lety +1

      @@liutomzhi yep i have that qu3estion too. i dont know why you move the j pointer when both heights are equal.
      why not move both pointers when they are both equal.

    • @skumakerguitar8708
      @skumakerguitar8708 Před 3 lety

      thats why we use

    • @thedataguyfromB
      @thedataguyfromB Před 3 lety

      Because we want to maximize the result
      Even though both heights are same we can't move both the pointer because if we do so we will miss the max possible ans
      Because here we are greedily searching for the two maximum height which are at the larger distance ( to maximize the width).
      Hope I answered your question.

  • @DilipYadav-yb4zf
    @DilipYadav-yb4zf Před 5 lety

    What is the logic of using left and right indexes?

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 5 lety

      That's what's actually helping us walk through the different combination of containers (the left and right form the start and end of our container respectively).

  • @neosapien247
    @neosapien247 Před 4 lety

    According to you what percentage of coders are just ‘born with it’ as opposed to ‘worked their asses off to get good at it’?

  • @EqualConnectCoach
    @EqualConnectCoach Před 4 lety

    One more approach, find the two maximum value from the array and find their index, now formula Is area = second-highest value (this is hight) *(index of first highest value - index of the second-highest value) (this is width), Note: here you need to subtract from highest index to lowest index

  • @eliojordanlopes2883
    @eliojordanlopes2883 Před 3 lety

    awesome !!!

  • @chaningname
    @chaningname Před 3 lety

    max area can also be 8*8=64. Why was 49 selected as maximum area?

  • @abhayakumarmishra5635
    @abhayakumarmishra5635 Před 4 lety +1

    Hi Kevin , at 7.14 , what will happen if h[I]=h[j] ?

    • @prathamj2215
      @prathamj2215 Před 3 lety

      I have the same exact question, did you get the answer?

  • @debayondharchowdhury2680

    This is brilliant.

  • @ishan_kumar
    @ishan_kumar Před 5 lety +1

    Good boy Kevin

  • @ahmedbouali7000
    @ahmedbouali7000 Před 4 lety

    The first solution was not accepted for me (time limit exceeded) ..
    (Same algorithm but with C++)

  • @dikshitbatra
    @dikshitbatra Před 4 lety

    Thanks.

  • @tirthjayswal9895
    @tirthjayswal9895 Před 4 lety

    Awsome

  • @code7434
    @code7434 Před 4 lety

    Cool

  • @skumakerguitar8708
    @skumakerguitar8708 Před 3 lety

    hi why we calculate (j-i) i'm so confused with this :( help me out

    • @isha5804
      @isha5804 Před 3 lety

      area = base * height, height is max value, base value will be the x axis, when you subtract j-i

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

    why it works ?

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 5 lety +1

      It's a greedy approach where we use two pointers to continuously look for a container that would hold more water than we have currently found

  • @marcelagomez9508
    @marcelagomez9508 Před 4 lety

    Hey guy thanks for making these daily coding question interviews. I have a first round interview with Amazon sometime in the next 5-10 days. I've done about 85 easy level leet code questions so far. Could yo recommend a plan of attack on which questions to focus on? I hear they have 14 leadership principles. I want to be ready for the technical part too.

  • @ahmedfattah5879
    @ahmedfattah5879 Před 3 lety

    for both who wonder what will happen if we have equal numbers basically we will try recursively both , it will be like this
    int fixConflict(vector& height,int s ,int e)
    {
    if(s>=e)
    return -1;
    int mymax=min(height[s],height[e])*(e-s);
    if(height[e]height[s]){
    mymax=max(mymax,fixConflict(height,++s,e));
    }
    else{
    mymax=max(fixConflict(height,++s,e),max(mymax,fixConflict(height,s,--e)));
    }
    return mymax;
    }
    int maxArea(vector& height) {
    return fixConflict(height,0,height.size()-1);
    }

  • @chetanpatteparapu7600
    @chetanpatteparapu7600 Před 4 lety

    This time you forgot the error checking at the beginning :D

  • @prashantgupta808
    @prashantgupta808 Před 3 lety

    It looks like you have just solved this problem again to make the video, like you already have solved this problem and learn the solution first and then make the video since you don't even think of check for testcases, and directly submitting.

  • @swagatochatterjee7104
    @swagatochatterjee7104 Před 4 lety

    amx!!

  • @ajourney179
    @ajourney179 Před 5 lety

    who is behind u ?

  • @quocanhhbui8271
    @quocanhhbui8271 Před 5 lety +1

    I got the solution but I cant mathematically prove this is the optimal solution. Yikes

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 5 lety

      That's ok! I've never been asked to mathematically prove something during one of my interviews. I think a good way to try and prove that something is optimal is proof by contradiction...i.e. try think of a case where it won't yield the best possible result. I hope that helps!

    • @quocanhhbui8271
      @quocanhhbui8271 Před 5 lety

      @@KevinNaughtonJr Yep, I am currently trying to prove by contradiction and see where it goes. Many thanks, all the best to your channel

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 5 lety

      @@quocanhhbui8271 awesome lmk how it goes and thank you!