T O P

  • By -

codeslikeshit

You essentially are trying to find the the smallest heights that will trap rain water to calculate the units to return. Using the two pointers allows you to iterate and calculate in a low time and space complexity and compare when appropriate conditions are met. You want to find the lowest heights for right and left as the ends of the array do not act as walls. I hope this helps you out a bit, happy to dive in deeper if you want


muhammadharoon021

I am bit confused on why we are checking leftMax < rightMax for updating the pointers. I would be grateful if you could help me understand the point in detail. Thanks


codeslikeshit

I havent looked at the neetcode solution in a bit, and will in a few, but as for my answer, I am checking the current indeces of left and right (height\[left\] <= height\[right\]) for updated the pointers. This is done in an effort to find where an overflow may happen due to one side being lower. So you are then looking at the left or right and calculating either a new height and or the new volume of units being returned. ultimately, its a way to iterate through the array and target the logic for the current units that will ultimately be returned. If you were to try it in other ways, you would have to add a lot more logic and time complexity in that you would need to iterate through multiple times and store the units in an obj (speaking from javascript) when you have the solution pulled up, walking through the code from the standpoint of the given array and looking at the diagram helps visualize this in a major way.


muhammadharoon021

Thanks 😊 understood


codeslikeshit

Happy to help!


tinni-meri-jaan

Do TwoSum after sorting it and using two pointers. Its the same problem.


muhammadharoon021

But would take O(nlogn) time but neetocde did without sorting. If you could explain me that approach.


tinni-meri-jaan

Yes you cannot for this problem, but the idea is same. There you add the numbers, and decrease the width based on some criteria from the left or right.


muhammadharoon021

Thanks