Jeyaseelan Inbaraj’s Post

DSA Series ... 🚀 Two pointers approach (Last problem) Leetcode #42 (Level: Hard) Trapping Rain Water ... 🎯 Problem : Given an elevation map (the bars), calculate how much rainwater can be trapped between the "peaks". Working Principle ... 🧐 Simply take it as two walls for easy to understand, moving inward from the left and right sides. ** Pointers: Start one pointer at the very beginning (left) and one at the end (right). ** ** leftMax and rightMax for bottleneck ** ** trappedWater to hold water level values ** - By maintaining leftMax and rightMax variables and moving inward from both ends of the array, we can calculate the trapped water in a single pass. - If height[left] is smaller than height[right], we know the water level is bounded by the left side. So compare the height[left] with leftMax. * If it is greater than max value, replace leftMax value, otherwise add water level with trappedWater by minus max with current height. * Then move (Increase) the left pointer. - If height[right] is smaller than height[left], compare the height[right] with rightMax. * If it is greater than max value, replace rightMax value, otherwise add water level with trappedWater by minus max with current height. * Then move (Decrease) the right pointer. - If there is overtaken with left and right pointers, terminate the loop and return trappedWater. That's all ... 😎 * Time Complexity: O(n) - We only pass through the array once. * Space Complexity: O(1) - No extra arrays needed, just a few variables. Get in touch : ) ... 🚀 I'll see you all in next post(Chapter) that was about another approach in DSA "Sliding Window"... 🔥 If you have any suggestions or questions, comment or ping me ... 💬 #Java #CodingInterview #Algorithms #LeetCode #SoftwareEngineering #DataStructures #DSA #TwoPointers #TrappingRainWater

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories