#3061
Hard Database Calculate trapping rain water
Database
82.0% acceptance
Mar 31, 2026
14
6
No description available.
Solution
Pandas
Time O(n)
Space O(1)
# Table: Heights
#
# +-------------+------+
# | Column Name | Type |
# +-------------+------+
# | id | int |
# | height | int |
# +-------------+------+
# id is the primary key (column with unique values) for this table, and it is guaranteed to be in sequential order.
# Each row of this table contains an id and height.
#
# Write a solution to calculate the amount of rainwater can be trapped between the bars in the landscape, considering that each bar has a width of 1 unit.
#
# Return the result table in any order.
#
# The result format is in the following example.
#
# Example 1:
# Input:
# Heights table:
# +-----+--------+
# | id | height |
# +-----+--------+
# | 1 | 0 |
# | 2 | 1 |
# | 3 | 0 |
# | 4 | 2 |
# | 5 | 1 |
# | 6 | 0 |
# | 7 | 1 |
# | 8 | 3 |
# | 9 | 2 |
# | 10 | 1 |
# | 11 | 2 |
# | 12 | 1 |
# +-----+--------+
# Output:
# +---------------------+
# | total_trapped_water |
# +---------------------+
# | 6 |
# +---------------------+
# Explanation:
#
# The elevation map depicted above (in the black section) is graphically represented with the x-axis denoting the id and the y-axis representing the heights [0,1,0,2,1,0,1,3,2,1,2,1]. In this scenario, 6 units of rainwater are trapped within the blue section.
import pandas as pd
def calculate_trapped_rain_water(heights: pd.DataFrame) -> pd.DataFrame:
heights = heights.sort_values('id').reset_index(drop=True)
h = heights['height'].tolist()
n = len(h)
if n < 3:
return pd.DataFrame({'total_trapped_water': [0]})
left_max = [0] * n
right_max = [0] * n
left_max[0] = h[0]
for i in range(1, n):
left_max[i] = max(left_max[i-1], h[i])
right_max[n-1] = h[n-1]
for i in range(n-2, -1, -1):
right_max[i] = max(right_max[i+1], h[i])
total = sum(min(left_max[i], right_max[i]) - h[i] for i in range(n))
return pd.DataFrame({'total_trapped_water': [total]})