Watch 10 video solutions for Calculate Trapping Rain Water, a hard level problem involving Database. This walkthrough by NeetCode has 558,064 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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.
Problem Overview: You receive elevation heights representing bars in order. Water can be trapped between taller bars on the left and right. The task is to compute the total amount of water trapped after rainfall using database-style operations.
Approach 1: Prefix & Suffix Maximums via Subqueries (O(n) time, O(n) space)
The trapped water at position i depends on the tallest bar to its left and right. If you know left_max[i] and right_max[i], the water above that bar is min(left_max, right_max) - height. In SQL, you can compute these values using correlated subqueries or derived tables that scan earlier and later rows. After computing both maxima, iterate through the rows and sum the valid trapped water values. This approach mirrors the classic array solution but implemented with SQL scans, which increases query cost on large datasets.
Approach 2: Self Join Range Aggregation (O(n²) time, O(1) extra space)
A more brute-force SQL strategy joins each row with all rows to its left and right to compute the maximum height in those ranges. For each index, aggregate MAX(height) from rows with smaller positions and from rows with larger positions. Then calculate trapped water with the same min(left_max, right_max) - height formula and sum the results. This method is easy to reason about but expensive because every row performs range scans through joins.
Approach 3: Window Function + Summation (O(n) time, O(n) space)
The most efficient SQL solution uses window functions. Compute the running maximum from the left using MAX(height) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). Compute the right-side maximum using a reversed window order. These window columns give left_max and right_max for every row in a single pass. The trapped water per row becomes GREATEST(LEAST(left_max, right_max) - height, 0), and a final SUM() aggregates the result. This approach leverages modern database optimizations and avoids repeated scans, making it the preferred production query pattern.
Recommended for interviews: Start by explaining the classic prefix/suffix maximum idea to demonstrate the underlying algorithm. Then translate that logic into SQL using window functions. Interviewers expect the O(n) reasoning because it shows you understand the water trapping constraint: water at each position depends only on the highest boundaries on both sides.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Self Join Range Aggregation | O(n²) | O(1) | Conceptual baseline or when demonstrating the raw definition of left and right boundaries |
| Prefix & Suffix Maximums via Subqueries | O(n) | O(n) | When window functions are unavailable but derived tables or scans are acceptable |
| Window Function + Summation | O(n) | O(n) | Best modern SQL solution; efficient for large datasets using analytic window operations |