Monotonic Array / TwoPointer :Trapping Rain Water: Most Asked !!
Suyash Awathe
Serving Notice Period l Exploring Opportunity Software Engineer @ Virtusa l Spring Boot | REST l Microservices | Data Structures and Algorithm I System Design | Oracle Java Certified Associate SE8
Day 16/75 :
Problem : Trapping Rain Water -(Hard)
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Approach1: Monotonic Stack Approach ( leftMax and RightMax)
Monotonic Stack: Stack which maintains , element is specific order. (ascending/descending)
Here, We maintain two different Arrays for leftMax and rightMax,at each position.
领英推荐
Code:
Time Complexity : O(n)
Space Complexity : O(n) , As we maintain two different array for leftMax and rightMax.
Approach 2: Two Pointer
We bascically maintains two pointers left (assigned to leftMost height)and right(assigned to rightMost height).
Code:
Time Complexity: O(n)
Space Complexity: O(1) .As no extra space is used.