Trapping Rain Water - Complete Solution Guide
Trapping Rain Water is LeetCode problem 42, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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. Example 1: 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. Example 2: Input: height = [4,2,0,3,2,5] Output: 9 Constraints: n == height.length 1 <= n <= 2 * 10 4 0 <= height[i] <
Detailed Explanation
The "Trapping Rain Water" problem asks us to calculate the total amount of rainwater that can be trapped between bars of varying heights. Imagine an elevation map represented by an array of non-negative integers, where each integer represents the height of a bar with a width of 1. When it rains, some areas between the bars will fill with water. We need to find the total volume of trapped water. The input is an array of integers representing the height of each bar, and the output is a single integer representing the total trapped water.
Solution Approach
The provided code employs a two-pointer approach to solve the trapping rain water problem. It initializes two pointers, 'left' and 'right', at the beginning and end of the height array, respectively. It also maintains two variables, 'left_max' and 'right_max', to keep track of the maximum height encountered so far from the left and right sides. The algorithm iterates as long as the left pointer is less than the right pointer. In each iteration, it compares the heights at the left and right pointers. If the height at the left pointer is smaller, it checks if it's greater than or equal to the 'left_max'. If so, it updates 'left_max'. Otherwise, it calculates the trapped water at the left pointer by subtracting its height from 'left_max' and adds it to the total. The left pointer is then incremented. A similar process is performed for the right pointer if the height at the right pointer is smaller. This process continues until the left and right pointers meet. The core idea is to incrementally compute how much water can be contained at a specific position based on `left_max` and `right_max` and move towards the inner part of array.
Step-by-Step Algorithm
- Step 1: Initialize two pointers, 'left' to 0 and 'right' to len(height) - 1.
- Step 2: Initialize 'left_max' and 'right_max' to 0.
- Step 3: Initialize 'total_water' to 0.
- Step 4: While 'left' is less than 'right':
- Step 5: If height[left] < height[right]:
- Step 6: If height[left] >= left_max:
- Step 7: Update left_max = height[left]
- Step 8: Else:
- Step 9: Add (left_max - height[left]) to total_water
- Step 10: Increment 'left'
- Step 11: Else:
- Step 12: If height[right] >= right_max:
- Step 13: Update right_max = height[right]
- Step 14: Else:
- Step 15: Add (right_max - height[right]) to total_water
- Step 16: Decrement 'right'
- Step 17: Return total_water
Key Insights
- Insight 1: The amount of water that can be trapped at any bar is determined by the minimum of the maximum height to its left and the maximum height to its right, minus the height of the bar itself. If this value is positive, then water is trapped.
- Insight 2: The two-pointer approach is efficient because it allows us to simultaneously iterate from both ends of the array, updating the left and right maximum heights and calculating the trapped water in a single pass.
- Insight 3: Maintaining separate 'left_max' and 'right_max' variables enables the algorithm to calculate trapped water locally without the need for extra data structures or repeated computations.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array, Two Pointers, Dynamic Programming, Stack, Monotonic Stack.
Companies
Asked at: Accolite, Adobe, Airbnb, Amazon, American Express, Apple, Atlassian, BitGo, Bloomberg, ByteDance, Capgemini, Cisco, Citadel, Coveo, CrowdStrike, DE Shaw, EPAM Systems, Expedia, Flipkart, Goldman Sachs, Google, Grammarly, Groww, HashedIn, Hive, IBM, InMobi, Infosys, Intel, Intuit, Jane Street, MAQ Software, MakeMyTrip, Media.net, Meta, Microsoft, Moloco, Myntra, National Instruments, Navan, Navi, Nextdoor, Nutanix, Nvidia, Oracle, PayPal, Paytm, PhonePe, PubMatic, Publicis Sapient, Qualcomm, Roblox, SAP, Salesforce, Samsung, ServiceNow, Snowflake, Splunk, Sprinklr, Swiggy, Tekion, Tesla, TikTok, Turvo, Uber, Visa, Walmart Labs, Wix, X, Yahoo, Yandex, Zenefits, Zepto, Zeta, Zoho, Zopsmart, carwale, jio, redbus, tcs.