Given an array where each element represents the height of a bar in a histogram, calculate how much water would be trapped between the bars after it rains. The width of each bar is 1.
Input/Output Examples
plaintext
Example 1:
Input:
arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output: 6
Explanation: The array represents an elevation map where the water trapped between the bars is 6 units.
Example 2:
Input:
arr = [4, 2, 0, 3, 2, 5]
Output: 9
Explanation: The water trapped between the bars is 9 units.
Approach to implement Trapping Rain Water
- Two-Pointer Technique:
- Use two pointers,
leftandright, starting from the leftmost and rightmost positions of the array. Track the maximum heights encountered from both directions usingleft_maxandright_max.
- Use two pointers,
- Calculate Trapped Water:
- While
leftis less thanright, comparearr[left]andarr[right]:- If
arr[left]is less thanarr[right], check ifarr[left]is greater thanleft_max. If it is, updateleft_max; otherwise, add the difference betweenleft_maxandarr[left]to the trapped water. Increment theleftpointer. - If
arr[right]is less than or equal toarr[left], check ifarr[right]is greater thanright_max. If it is, updateright_max; otherwise, add the difference betweenright_maxandarr[right]to the trapped water. Decrement therightpointer.
- If
- While
- Continue Until Pointers Meet:
- Repeat the above process until the
leftandrightpointers meet. The trapped water will be accumulated in a variable.
- Repeat the above process until the
C++ Program to implement Trapping Rain Water
cpp
#include <iostream>
#include <vector>
using namespace std;
// Function to calculate the total trapped rainwater
int trapRainWater(vector<int>& arr) {
int left = 0, right = arr.size() - 1;
int left_max = 0, right_max = 0;
int water_trapped = 0;
// Traverse the elevation map with two pointers
while (left < right) {
if (arr[left] < arr[right]) {
// If the current height is greater than the left maximum, update it
if (arr[left] >= left_max) {
left_max = arr[left];
} else {
// Otherwise, add the trapped water at the current position
water_trapped += left_max - arr[left];
}
left++;
} else {
// If the current height is greater than the right maximum, update it
if (arr[right] >= right_max) {
right_max = arr[right];
} else {
// Otherwise, add the trapped water at the current position
water_trapped += right_max - arr[right];
}
right--;
}
}
return water_trapped;
}
int main() {
vector<int> arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int result = trapRainWater(arr);
cout << "Total water trapped: " << result << " units" << endl;
return 0;
}
Java Program to implement Trapping Rain Water
java
public class TrappingRainWater {
// Function to calculate the total trapped rainwater
public static int trapRainWater(int[] arr) {
int left = 0, right = arr.length - 1;
int left_max = 0, right_max = 0;
int water_trapped = 0;
// Traverse the elevation map with two pointers
while (left < right) {
if (arr[left] < arr[right]) {
// If the current height is greater than the left maximum, update it
if (arr[left] >= left_max) {
left_max = arr[left];
} else {
// Otherwise, add the trapped water at the current position
water_trapped += left_max - arr[left];
}
left++;
} else {
// If the current height is greater than the right maximum, update it
if (arr[right] >= right_max) {
right_max = arr[right];
} else {
// Otherwise, add the trapped water at the current position
water_trapped += right_max - arr[right];
}
right--;
}
}
return water_trapped;
}
public static void main(String[] args) {
int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int result = trapRainWater(arr);
System.out.println("Total water trapped: " + result + " units");
}
}
Python Program to implement Trapping Rain Water
python
# Function to calculate the total trapped rainwater
def trap_rain_water(arr):
left, right = 0, len(arr) - 1
left_max, right_max = 0, 0
water_trapped = 0
# Traverse the elevation map with two pointers
while left < right:
if arr[left] < arr[right]:
# If the current height is greater than the left maximum, update it
if arr[left] >= left_max:
left_max = arr[left]
else:
# Otherwise, add the trapped water at the current position
water_trapped += left_max - arr[left]
left += 1
else:
# If the current height is greater than the right maximum, update it
if arr[right] >= right_max:
right_max = arr[right]
else:
# Otherwise, add the trapped water at the current position
water_trapped += right_max - arr[right]
right -= 1
return water_trapped
# Example usage
if __name__ == "__main__":
arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
result = trap_rain_water(arr)
print("Total water trapped:", result, "units")
Time Complexity:
- O(n): Each element of the array is processed once.
Space Complexity:
- O(1): The algorithm uses a constant amount of extra space.