ExamAdda Logo

Trapping Rain Water

Easy

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water can be trapped after raining.

Example 1

Input

12
0 1 0 2 1 0 1 3 2 1 2 1

Output

6

Explanation

The elevation map traps water between taller bars.

The total amount of trapped water is 6 units.

Example 2

Input

6
4 2 0 3 2 5

Output

9

Explanation

The water trapped above each bar adds up to 9 units.

Constraints

1 ≤ height.length ≤ 2 × 10⁴
0 ≤ height[i] ≤ 10⁵

Hints:

Hint 1

The water trapped at an index depends on the tallest bar to its left and the tallest bar to its right.

Hint 2

Use two pointers starting from both ends while maintaining the maximum height seen from each side. Move the pointer with the smaller maximum height and accumulate trapped water.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 4, 2026

Last updated

Aug 4, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output