Arrays January 17 ,2026

Trapping Rain Water

Problem Statement

You are given an array height[] of non-negative integers where each element represents the height of a bar and the width of each bar is 1.

Calculate how much rainwater can be trapped between the bars after raining.

Example 1

Input

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

Output

6

Explanation
Water trapped at each index:

Index:  0 1 2 3 4 5 6 7 8 9 10 11
Water:  0 0 1 0 1 2 1 0 0 1  0  0

Total water = 6

Example 2

Input

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

Output

9

Why This Problem Is Important

  • Very frequently asked interview problem
  • Appears in FAANG & top product companies
  • Tests two-pointer & prefix logic
  • Classic array + geometry problem
  • Helps understand space optimization
  • Popular medium-level question

Approaches Overview

ApproachTechniqueTimeSpace
Approach 1Brute ForceO(n²)O(1)
Approach 2Prefix & Suffix ArraysO(n)O(n)
Approach 3Two Pointers (Optimal)O(n)O(1)

Approach 1: Brute Force

Idea

For each bar, find the maximum height to its left and maximum height to its right.
Water at index i:

min(leftMax, rightMax) - height[i]

Algorithm

  1. For each index i
  2. Find max height on left
  3. Find max height on right
  4. Add trapped water if positive

Time & Space Complexity

  • Time: O(n²)
  • Space: O(1)

Implementations

C

#include 

int main() {
    int h[] = {0,1,0,2,1,0,1,3,2,1,2,1};
    int n = 12, water = 0;

    for(int i = 0; i < n; i++) {
        int leftMax = 0, rightMax = 0;

        for(int j = 0; j <= i; j++)
            if(h[j] > leftMax) leftMax = h[j];

        for(int j = i; j < n; j++)
            if(h[j] > rightMax) rightMax = h[j];

        int trapped = (leftMax < rightMax ? leftMax : rightMax) - h[i];
        if(trapped > 0)
            water += trapped;
    }

    printf("%d", water);
    return 0;
}

C++

#include 
using namespace std;

int main() {
    int h[] = {0,1,0,2,1,0,1,3,2,1,2,1};
    int n = 12, water = 0;

    for(int i = 0; i < n; i++) {
        int leftMax = 0, rightMax = 0;

        for(int j = 0; j <= i; j++)
            leftMax = max(leftMax, h[j]);

        for(int j = i; j < n; j++)
            rightMax = max(rightMax, h[j]);

        water += max(0, min(leftMax, rightMax) - h[i]);
    }

    cout << water;
    return 0;
}

Java

public class TrappingRainWater {
    public static void main(String[] args) {
        int[] h = {0,1,0,2,1,0,1,3,2,1,2,1};
        int water = 0;

        for(int i = 0; i < h.length; i++) {
            int leftMax = 0, rightMax = 0;

            for(int j = 0; j <= i; j++)
                leftMax = Math.max(leftMax, h[j]);

            for(int j = i; j < h.length; j++)
                rightMax = Math.max(rightMax, h[j]);

            water += Math.max(0, Math.min(leftMax, rightMax) - h[i]);
        }

        System.out.print(water);
    }
}

Python

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

for i in range(len(height)):
    leftMax = max(height[:i+1])
    rightMax = max(height[i:])
    water += max(0, min(leftMax, rightMax) - height[i])

print(water)

JavaScript

let height = [0,1,0,2,1,0,1,3,2,1,2,1];
let water = 0;

for (let i = 0; i < height.length; i++) {
    let leftMax = 0, rightMax = 0;

    for (let j = 0; j <= i; j++)
        leftMax = Math.max(leftMax, height[j]);

    for (let j = i; j < height.length; j++)
        rightMax = Math.max(rightMax, height[j]);

    water += Math.max(0, Math.min(leftMax, rightMax) - height[i]);
}

console.log(water);

Approach 2: Prefix & Suffix Arrays

Idea

Precompute:

  • leftMax[i] → max height to the left
  • rightMax[i] → max height to the right

Algorithm

  1. Build leftMax array
  2. Build rightMax array
  3. Sum min(leftMax[i], rightMax[i]) - height[i]

Time & Space Complexity

  • Time: O(n)
  • Space: O(n)

Implementations

C++

#include 
using namespace std;

int main() {
    int h[] = {0,1,0,2,1,0,1,3,2,1,2,1};
    int n = 12;
    int left[12], right[12];

    left[0] = h[0];
    for(int i = 1; i < n; i++)
        left[i] = max(left[i-1], h[i]);

    right[n-1] = h[n-1];
    for(int i = n-2; i >= 0; i--)
        right[i] = max(right[i+1], h[i]);

    int water = 0;
    for(int i = 0; i < n; i++)
        water += max(0, min(left[i], right[i]) - h[i]);

    cout << water;
    return 0;
}

Python

height = [0,1,0,2,1,0,1,3,2,1,2,1]
n = len(height)

left = [0]*n
right = [0]*n

left[0] = height[0]
for i in range(1, n):
    left[i] = max(left[i-1], height[i])

right[n-1] = height[n-1]
for i in range(n-2, -1, -1):
    right[i] = max(right[i+1], height[i])

water = 0
for i in range(n):
    water += max(0, min(left[i], right[i]) - height[i])

print(water)

Approach 3: Two Pointers (Optimal)

Idea

Use two pointers from both ends and maintain:

  • leftMax
  • rightMax

Water is decided by the smaller side.

Algorithm

  1. Initialize l = 0, r = n-1
  2. Maintain leftMax, rightMax
  3. Move the pointer with smaller height
  4. Add trapped water accordingly

Time & Space Complexity

  • Time: O(n)
  • Space: O(1)

Implementations

C++

#include 
using namespace std;

int main() {
    int h[] = {0,1,0,2,1,0,1,3,2,1,2,1};
    int n = 12;
    int l = 0, r = n - 1;
    int leftMax = 0, rightMax = 0, water = 0;

    while(l < r) {
        if(h[l] <= h[r]) {
            leftMax = max(leftMax, h[l]);
            water += leftMax - h[l];
            l++;
        } else {
            rightMax = max(rightMax, h[r]);
            water += rightMax - h[r];
            r--;
        }
    }

    cout << water;
    return 0;
}

Java

public class TrappingRainWater {
    public static void main(String[] args) {
        int[] h = {0,1,0,2,1,0,1,3,2,1,2,1};
        int l = 0, r = h.length - 1;
        int leftMax = 0, rightMax = 0, water = 0;

        while(l < r) {
            if(h[l] <= h[r]) {
                leftMax = Math.max(leftMax, h[l]);
                water += leftMax - h[l];
                l++;
            } else {
                rightMax = Math.max(rightMax, h[r]);
                water += rightMax - h[r];
                r--;
            }
        }

        System.out.print(water);
    }
}

Python

height = [0,1,0,2,1,0,1,3,2,1,2,1]
l, r = 0, len(height) - 1
leftMax = rightMax = water = 0

while l < r:
    if height[l] <= height[r]:
        leftMax = max(leftMax, height[l])
        water += leftMax - height[l]
        l += 1
    else:
        rightMax = max(rightMax, height[r])
        water += rightMax - height[r]
        r -= 1

print(water)

JavaScript

let height = [0,1,0,2,1,0,1,3,2,1,2,1];
let l = 0, r = height.length - 1;
let leftMax = 0, rightMax = 0, water = 0;

while (l < r) {
    if (height[l] <= height[r]) {
        leftMax = Math.max(leftMax, height[l]);
        water += leftMax - height[l];
        l++;
    } else {
        rightMax = Math.max(rightMax, height[r]);
        water += rightMax - height[r];
        r--;
    }
}

console.log(water);

Dry Run (Two Pointers)

Input

[0,1,0,2,1,0,1,3,2,1,2,1]

Water added step-by-step → 6 units

Summary

  • Brute force is slow
  • Prefix-suffix improves time
  • Two-pointer is optimal & interview-preferred
  • Classic problem to master arrays

Next Problem in the Series

Maximum Circular Subarray Sum

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com