Skip to content

ORIGINAL CODING QUESTION

Rain storage between walls

Walls have unit width and nonnegative integer heights. Return the total water trapped after rain.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n heights. Print the total trapped water.

Constraints

1 ≤ n ≤ 10,000; 0 ≤ height ≤ 10,000.

Example 1

Input

5
3 0 2 0 4

Output

7

The inner positions hold 3, 1 and 3 units, totaling 7.

Example 2

Input

3
1 2 3

Output

0

An increasing profile traps no water.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

At each position, water depends on the smaller of the largest walls on both sides.

Hint 2

Prefix and suffix maximum arrays provide a linear-time approach.

Hint 3

A two-pointer approach can reduce extra space by advancing the side with the smaller known boundary.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →