42. Trapping Rain Water
Table of Contents
ToggleDifficulty: 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.
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<code>1 <= n <= 2 * 104<code>0 <= height[i] <= 105
Solution:
To solve this problem, we can follow these steps:
- Initialize two pointers:
leftstarting at the beginning andrightat the end of the elevation array. - Track maximum heights: Use
left_maxandright_maxto track the maximum heights encountered from the left and right sides, respectively. - Move pointers towards each other: At each step, move the pointer with the smaller height inward and update the trapped water amount based on the minimum of
left_maxandright_max.
Let’s implement this solution in PHP: 42. Trapping Rain Water
<?php
// Example usage:
$height = [0,1,0,2,1,0,1,3,2,1,2,1];
echo trap($height); // Output: 6
$height = [4,2,0,3,2,5];
echo trap($height); // Output: 9
?>
Explanation:
- Initialize pointers and maximum heights: Start with
leftat the beginning andrightat the end of theheightarray. Also, initializeleft_maxandright_maxto0. - Traverse the array with two pointers:
- Compare
height[left]andheight[right]. - If
height[left]is less than or equal toheight[right]:- If
height[left]is greater than or equal toleft_max, updateleft_max. - Otherwise, calculate the water trapped at
leftand add towater. - Move
leftpointer one step to the right.
- If
- If
height[right]is less thanheight[left]:- If
height[right]is greater than or equal toright_max, updateright_max. - Otherwise, calculate the water trapped at
rightand add towater. - Move
rightpointer one step to the left.
- If
- Compare
- Return the total trapped water: Once the two pointers meet, the
watervariable holds the total amount of trapped rainwater.
This approach efficiently computes the amount of trapped rainwater by leveraging the two-pointer technique and avoids the need for additional space, making it optimal for large input sizes.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
Read More

