Trapping Rain Water
Real-world version: Level Flood CapacityThe statement here is our own: the same inputs, outputs and technique.
You are writing the flood tool for a 2D platformer level editor. A level's terrain is stored as an integer array columns, where columns[i] is how many solid one-by-one tiles are stacked in column i. Tiles in a column sit flush on the floor with no gaps above or below them, and the columns are laid out side by side from left to right.
When the designer presses Flood, liquid pours in from above until no more will stay, and then anything that can get out drains away. Liquid gets out by moving sideways into an empty cell at the same height and continuing until it leaves the map past the left or right edge; solid tiles block that movement. Liquid with no route off the map stays where it is.
Return the number of one-by-one cells still holding liquid once the level has settled.
Examples
Example 1
- Input
- columns = [0, 3, 1, 0, 2, 1, 4]
- Output
- 8
Column 0 is open to the left edge, so nothing rests there. The four dips between the stacks of 3 and 4 are walled in on both sides and fill to height 3, holding 2 + 3 + 1 + 2 = 8 cells.
Example 2
- Input
- columns = [5, 2, 8, 3, 4]
- Output
- 4
Column 1 fills to height 5, the limit set by the stack of 5 on its left, holding 3 cells. Column 3 only fills to height 4, the limit set by the stack of 4 on its right, holding 1 cell. Different sides decide the two answers.
Example 3
- Input
- columns = [2, 3, 3, 7]
- Output
- 0
The terrain never steps back down, so every cell above it has a clear path off the right edge.
Constraints
- n == columns.length
- 1 <= n <= 2 * 10^4
- 0 <= columns[i] <= 10^5
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def flood_capacity(columns: list[int]) -> int:public int floodCapacity(int[] columns)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 17 test cases: 17 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Sum of Subarray MinimumsReal-world version: Weakest Reading Per StretchMedium
- Shortest Unsorted Continuous SubarrayReal-world version: Shortest Stretch to Re-sortMedium
- Maximum Width RampReal-world version: Widest Span That Does Not FallMedium
- Shortest Subarray to be Removed to Make Array SortedReal-world version: Cutting One Stretch to Leave the Gauges RisingMedium