Resource · Guide or article
Rain Terraces (Trapping Rain Water) Problem
Works through the trapping rain water problem, computing water held above each bar from the tallest bars on its left and right. A strong fit for array and DP interview prep.
Reviewed
Open the original: Rain Terraces (Trapping Rain Water) Problem (opens the original site in a new tab)Add to a roadmap
Keep this resource with a roadmap you follow. It appears as your own extra resource; the roadmap's steps don't change and it doesn't count toward your tracked steps.
Source content: English
Given an array of non-negative integers representing terraces in an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. An element of array can store water if there are higher bars on left and right. We can find amount of water to be stored in every element by finding the heights of bars on left and right sides. The idea is to compute amount of water that can be stored in every element of array. For example, consider the array [3, 0, 0, 2, 0, 4], We can trap "3*2 units" of water between 3 an 2, "1 unit" on top of bar 2 and "3 units" between 2 and 4. See below diagram also. For each element in the array, we find the maximum level of water it can trap after the rain, which is equal to the minimum of maximum height of bars on both the sides minus its own height.
PrepKit overview
PrepKit editors wrote and reviewed this overview from the source repository. It is not text from the resource itself.
- Suited to
- The source does not state a level
- Format
- Lesson
What it covers
- Three examples with ASCII drawings and outputs of 2, 10 and 6
- Brute force that scans left and right for every bar, O(n^2) time and O(1) extra space
- DP version that precomputes left_max and right_max arrays, O(n) time and O(n) extra space
- States the per-bar formula: the smaller of the two maxima minus the bar's height
How to use it
PrepKit study advice, not a claim made by the source.
Draw example 3 on grid paper and fill in the water, then code the DP version and check you get 6. As a stretch, find an O(1)-space method; the page does not cover it.
Scope and limitations
Stops at the DP approach, with no two-pointer solution. Some illustrations are GeeksForGeeks and LeetCode images.
Access and format
README on GitHub in trekhleb/javascript-algorithms (MIT). English, free.
Reviewed by PrepKit on Oct 2, 2026. Listing source commit: 85293e3e2b88
Evidence behind this overview
- src/algorithms/uncategorized/rain-terraces/README.md
Pages that include this
Get the PrepKit newsletter
Optional. You don't need it to use PrepKit.