Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Solve trapping rain water using two pointers

Compute how much water can be trapped after raining given an elevation map using an optimal two-pointer method.

Python practice30 minTwo Pointers & Sliding WindowAdvancedLast updated March 26, 2026

Problem statement

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Implement an algorithm using two pointers that runs in linear time and uses constant extra space.

Task

Apply the two-pointer technique to calculate trapped rain water in O(n) time and O(1) extra space.

Examples

Example with multiple pits

Input

height = [0,1,0,2,1,0,1,3,2,1,2,1]

Output

6

The elevation map traps 6 units of water in total.

Input format

Call trap_rain_water(height) where height is a list of non-negative integers.

Output format

Return an integer indicating total trapped water.

Constraints

0 <= len(height) <= 10^5, 0 <= height[i] <= 10^5. Use O(1) extra space and O(n) time.

Samples

Sample 1

Input

[4,2,0,3,2,5]

Output

9

Classic example with total trapped water equal to 9.