Trapping Rainwater in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
int main(){
    int a[]={3,0,2,0,4},n=5,l[5],r[5],water=0;
    l[0]=a[0]; for(int i=1;i<n;i++) l[i]=l[i-1]>a[i]?l[i-1]:a[i];
    r[n-1]=a[n-1]; for(int i=n-2;i>=0;i--) r[i]=r[i+1]>a[i]?r[i+1]:a[i];
    for(int i=0;i<n;i++) water+= (l[i]<r[i]?l[i]:r[i]) - a[i];
    printf("%d",water);
}

C Output

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

Output:  
9


C++ Program

#include <bits/stdc++.h>
using namespace std;
int main(){
    vector<int> a={3,0,2,0,4}; int n=a.size(),water=0;
    vector<int> l(n),r(n);
    l[0]=a[0]; for(int i=1;i<n;i++) l[i]=max(l[i-1],a[i]);
    r[n-1]=a[n-1]; for(int i=n-2;i>=0;i--) r[i]=max(r[i+1],a[i]);
    for(int i=0;i<n;i++) water+=min(l[i],r[i])-a[i];
    cout<<water;
}

C++ Output

Input:  
[2,0,2]  

Output:  
2


JAVA Program

class Main{
    public static void main(String[] args){
        int[] a={3,0,2,0,4}; int n=a.length, water=0;
        int[] l=new int[n], r=new int[n];
        l[0]=a[0]; for(int i=1;i<n;i++) l[i]=Math.max(l[i-1],a[i]);
        r[n-1]=a[n-1]; for(int i=n-2;i>=0;i--) r[i]=Math.max(r[i+1],a[i]);
        for(int i=0;i<n;i++) water+=Math.min(l[i],r[i])-a[i];
        System.out.println(water);
    }
}

JAVA Output

Input:  
[5,1,2,1,5] 

Output:  
14


Python Program

a=[3,0,2,0,4]; n=len(a)
l=[0]*n; r=[0]*n
l[0]=a[0]
for i in range(1,n): l[i]=max(l[i-1],a[i])
r[-1]=a[-1]
for i in range(n-2,-1,-1): r[i]=max(r[i+1],a[i])
print(sum(min(l[i],r[i])-a[i] for i in range(n)))

Python Output

Input:  
[0,1,0,2,1,0,1,3,2,1,2,1]

Output:  
6


Deep Explanation
Example
Let's imagine the bars:


Height: 3   0   2   0   4
Index:  0   1   2   3   4
Water can be trapped only if there are higher bars on left and right sides. Water trapped at every index =

min(max height to the left, max height to the right) - current height
If this value is less than zero, then no water can be trapped there.

Real-Life Analogy
Consider buildings in a city after raining. Suppose two high buildings are standing with a low one in between. Rainwater would fill the gap up to the level of the shorter building. This is precisely what we calculate here — the trapped water is calculated by the smaller of the two highest structures on either side.

Step-by-Step for [3,0,2,0,4]
Left max array (l): Store the tallest bar from the left.


l = [3, 3, 3, 3, 4]
Right max array (r): Store the tallest bar from the right.


r = [4, 4, 4, 4, 4]
Water at each index:


i=0: min(3,4)-3 = 0
i=1: min(3,4)-0 = 3
i=2: min(3,4)-2 = 1
i=3: min(3,4)-0 = 3
i=4: min(4,4)-4 = 0
Total = 0+3+1+3+0 = 7 units.

Why This Works
Water is only possible if there exists a container shape — i.e., taller bars surround a valley.
By computing the maximum height of the tallest bar to the left and right of every index once, we do not have to scan again, decreasing the time complexity from O(n²) to O(n).

Memory and Optimization
The method employs O(n) additional space for l and r arrays.
There's even a two-pointer solution that achieves this in O(1) additional space by having left and right pointers and keeping dynamic track of left_max and right_max.

Common Beginner Issues
Not checking both sides for max height.

Going with just max-to-left or max-to-right results in wrong output.

Failing to account for arrays of size < 3 (where no water can be trapped).

Applications in Real Life
The problem occurs in:

Computer graphics (simulating 3D water).

Civil engineering (rainwater drainage between structures).

Game development (liquid dynamics on terrain).

Interview Relevance
This is a traditional array + precomputation problem.
It checks if you can optimize naive scanning into one pass with stored values.
It usually comes as a sequel to "max subarray" or "next greater element" problems.

SEO-Friendly Summary
The Trapping Rainwater is a well-known problem in algorithms that demonstrates how to convert a naive O(n²) solution to a very efficient O(n) solution using precomputed maximum values from both ends. Through this approach, programmers learn how to optimize array traversal, deal with auxiliary data structures, and solve problems where the answer at each position is based on data from both ends. Whether during coding interviews, competitive programming, or actual projects that require terrain modeling or fluid simulation, having dominion over the rainwater trapping logic provides you with a precious advantage in coding efficacious and high-performance code.