Ctrl K

Water Between Walls

Hard
A landscape is given by the array walls: walls[i] is the height of a column of width 1, and the columns stand side by side from left to right. After a rain, water stays wherever it is held on both sides by taller columns; whatever is not held runs off the ends. Return the total amount of water, in unit cells, that stays on the landscape.
Example 1
walls=[3, 0, 2, 0, 4] → 7

Over columns 1–3 the water level is capped by the left wall of height 3, giving 3 + 1 + 3 = 7 units.

Example 2
walls=[1, 2, 3, 2, 1] → 0

The profile only rises and then falls, so there is no dip and all the water runs off.

Example 3
walls=[5, 1, 1, 6, 2, 3] → 9

Between the walls 5 and 6 the water stands at level 5: 4 units over each of two columns. Between 6 and 3 there is 1 more over the column of height 2. Total 9.

Constraints
  • 1 ≤ length of walls ≤ 2 · 10⁴
  • 0 ≤ walls[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Solid Panel Block HardLargest Number From Two Rows HardFrog on the Posts HardRaising by Ranges HardWidest Fence Span Around the Marked Board Hard
loading Python…
Input
walls=[3, 0, 2, 0, 4]
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 131 tests on the server, hidden ones included.