Given an array arr[] of size n consisting of non-negative integers, where each element represents the height of a bar in an elevation map and the width of each bar is 1, determine the total amount of water that can be trapped between the bars after it rains.
Trapping Rainwater Problem
Examples:
Input: arr[] = [3, 0, 1, 0, 4, 0, 2] Output: 10 Explanation: The expected rainwater to be trapped is shown in the above image.
To trap water at any index in the elevation map, there must be taller bars on both its left and right sides. The water that can be stored at each position is determined by the height of the shorter of the two boundaries (left and right), minus the height of the current bar.
We compute the trapped water at each index as: min(leftMax, rightMax) - height[i], if this value is positive.
The total trapped water is the sum of water stored at all valid indices.
If either side lacks a boundary, no water can be trapped at that position.
[Naive Approach] Brute Force - O(n^2) Time and O(1) Space
Traverse every array element and find the highest bars on the left and right sides. Take the smaller of two heights. The difference between the smaller height and the height of the current element is the amount of water that can be stored in this array element.
C++
#include<iostream>#include<vector>usingnamespacestd;intmaxWater(vector<int>&arr){intres=0;// For every element of the arrayfor(inti=1;i<arr.size()-1;i++){// Find the maximum element on its leftintleft=arr[i];for(intj=0;j<i;j++)left=max(left,arr[j]);// Find the maximum element on its rightintright=arr[i];for(intj=i+1;j<arr.size();j++)right=max(right,arr[j]);// Update the maximum waterres+=(min(left,right)-arr[i]);}returnres;}intmain(){vector<int>arr={2,1,5,3,1,0,4};cout<<maxWater(arr);return0;}
C
#include<stdio.h>intmaxWater(intarr[],intn){intres=0;// For every element of the arrayfor(inti=1;i<n-1;i++){// Find the maximum element on its leftintleft=arr[i];for(intj=0;j<i;j++)if(arr[j]>left)left=arr[j];// Find the maximum element on its rightintright=arr[i];for(intj=i+1;j<n;j++)if(arr[j]>right)right=arr[j];// Update the maximum waterres+=(left<right?left:right)-arr[i];}returnres;}// Driver codeintmain(){intarr[]={2,1,5,3,1,0,4};intn=sizeof(arr)/sizeof(arr[0]);printf("%d",maxWater(arr,n));return0;}
Java
classGFG{staticintmaxWater(int[]arr){intres=0;// For every element of the arrayfor(inti=1;i<arr.length-1;i++){// Find the maximum element on its leftintleft=arr[i];for(intj=0;j<i;j++)left=Math.max(left,arr[j]);// Find the maximum element on its rightintright=arr[i];for(intj=i+1;j<arr.length;j++)right=Math.max(right,arr[j]);// Update the maximum waterres+=Math.min(left,right)-arr[i];}returnres;}publicstaticvoidmain(String[]args){int[]arr={2,1,5,3,1,0,4};System.out.println(maxWater(arr));}}
Python
defmaxWater(arr):res=0# For every element of the arrayforiinrange(1,len(arr)-1):# Find the maximum element on its leftleft=arr[i]forjinrange(i):left=max(left,arr[j])# Find the maximum element on its rightright=arr[i]forjinrange(i+1,len(arr)):right=max(right,arr[j])# Update the maximum waterres+=(min(left,right)-arr[i])returnresif__name__=="__main__":arr=[2,1,5,3,1,0,4]print(maxWater(arr))
C#
usingSystem;classGFG{staticintmaxWater(int[]arr){intres=0;// For every element of the arrayfor(inti=1;i<arr.Length-1;i++){// Find the maximum element on its leftintleft=arr[i];for(intj=0;j<i;j++)left=Math.Max(left,arr[j]);// Find the maximum element on its rightintright=arr[i];for(intj=i+1;j<arr.Length;j++)right=Math.Max(right,arr[j]);// Update the maximum waterres+=Math.Min(left,right)-arr[i];}returnres;}staticvoidMain(){int[]arr={2,1,5,3,1,0,4};Console.WriteLine(maxWater(arr));}}
JavaScript
functionmaxWater(arr){letres=0;// For every element of the arrayfor(leti=1;i<arr.length-1;i++){// Find the maximum element on its leftletleft=arr[i];for(letj=0;j<i;j++)left=Math.max(left,arr[j]);// Find the maximum element on its rightletright=arr[i];for(letj=i+1;j<arr.length;j++)right=Math.max(right,arr[j]);// Update the maximum waterres+=Math.min(left,right)-arr[i];}returnres;}// Driver codeletarr=[2,1,5,3,1,0,4];console.log(maxWater(arr));
Output
9
[Better Approach] Prefix and suffix max for each index - O(n) Time and O(n) Space
In the previous approach, for every element, we calculated the highest bar on its left and right separately, resulting in O(n²) time.
To reduce the time complexity:
Precompute and store the highest bar on the left and right in left[] and right[].
Then, use these values to calculate the water stored at each index:
min(left[i], right[i]) - arr[i]
This reduces the time complexity to O(n), with O(n) extra space.
C++
#include<iostream>#include<vector>usingnamespacestd;intmaxWater(vector<int>&arr){intn=arr.size();// left[i] contains height of tallest bar to the// left of i'th bar including itselfvector<int>left(n);// right[i] contains height of tallest bar to// the right of i'th bar including itselfvector<int>right(n);intres=0;// fill left arrayleft[0]=arr[0];for(inti=1;i<n;i++)left[i]=max(left[i-1],arr[i]);// fill right arrayright[n-1]=arr[n-1];for(inti=n-2;i>=0;i--)right[i]=max(right[i+1],arr[i]);// calculate the accumulated water element by elementfor(inti=1;i<n-1;i++){intminOf2=min(left[i],right[i]);res+=minOf2-arr[i];}returnres;}intmain(){vector<int>arr={2,1,5,3,1,0,4};cout<<maxWater(arr);return0;}
C
#include<stdio.h>intmaxWater(intarr[],intn){// left[i] contains height of tallest bar to the// left of i'th bar including itselfintleft[n];// right[i] contains height of tallest bar to// the right of i'th bar including itselfintright[n];intres=0;// fill left arrayleft[0]=arr[0];for(inti=1;i<n;i++)left[i]=left[i-1]>arr[i]?left[i-1]:arr[i];// fill right arrayright[n-1]=arr[n-1];for(inti=n-2;i>=0;i--)right[i]=right[i+1]>arr[i]?right[i+1]:arr[i];// calcualte the accumulated water element by elementfor(inti=1;i<n-1;i++){intminOf2=left[i]<right[i]?left[i]:right[i];res+=minOf2-arr[i];}returnres;}intmain(){intarr[]={2,1,5,3,1,0,4};intn=sizeof(arr)/sizeof(arr[0]);printf("%d",maxWater(arr,n));return0;}
Java
publicclassGFG{publicstaticintmaxWater(int[]arr){intn=arr.length;int[]left=newint[n];int[]right=newint[n];intres=0;// fill left arrayleft[0]=arr[0];for(inti=1;i<n;i++){left[i]=Math.max(left[i-1],arr[i]);}// fill right arrayright[n-1]=arr[n-1];for(inti=n-2;i>=0;i--){right[i]=Math.max(right[i+1],arr[i]);}// calculate the accumulated water element by elementfor(inti=1;i<n-1;i++){intminOf2=Math.min(left[i],right[i]);res+=minOf2-arr[i];}returnres;}publicstaticvoidmain(String[]args){int[]arr={2,1,5,3,1,0,4};System.out.println(maxWater(arr));}}
Python
defmaxWater(arr):n=len(arr)# left arrayleft=[0]*n# right arrayright=[0]*nres=0# fill left arrayleft[0]=arr[0]foriinrange(1,n):left[i]=max(left[i-1],arr[i])# fill right arrayright[n-1]=arr[n-1]foriinrange(n-2,-1,-1):right[i]=max(right[i+1],arr[i])# calculate the accumulated water element by elementforiinrange(1,n-1):min_of_2=min(left[i],right[i])res+=min_of_2-arr[i]returnresif__name__=="__main__":arr=[2,1,5,3,1,0,4]print(maxWater(arr))
C#
usingSystem;classGFG{staticintmaxWater(int[]arr){intn=arr.Length;int[]left=newint[n];int[]right=newint[n];intres=0;// fill left arrayleft[0]=arr[0];for(inti=1;i<n;i++){left[i]=Math.Max(left[i-1],arr[i]);}// fill right arrayright[n-1]=arr[n-1];for(inti=n-2;i>=0;i--){right[i]=Math.Max(right[i+1],arr[i]);}// calculate the accumulated water // element by elementfor(inti=1;i<n-1;i++){intminOf2=Math.Min(left[i],right[i]);res+=minOf2-arr[i];}returnres;}staticvoidMain(){int[]arr={2,1,5,3,1,0,4};Console.WriteLine(maxWater(arr));}}
JavaScript
functionmaxWater(arr){constn=arr.length;letleft=Array(n);letright=Array(n);letres=0;// fill left arrayleft[0]=arr[0];for(leti=1;i<n;i++){left[i]=Math.max(left[i-1],arr[i]);}// fill right arrayright[n-1]=arr[n-1];for(leti=n-2;i>=0;i--){right[i]=Math.max(right[i+1],arr[i]);}// calculate the accumulated water element// by elementfor(leti=1;i<n-1;i++){letminOf2=Math.min(left[i],right[i]);res+=minOf2-arr[i];}returnres;}// Driver Codeconstarr=[2,1,5,3,1,0,4];console.log(maxWater(arr));
Output
9
[Expected Approach] Using Two Pointers - O(n) Time and O(1) Space
The approach is based on the following observations:
For a subarray `arr[left...right]`, we maintain the maximum height on the left (`leftMax`) and on the right (`rightMax`).
If `leftMax < rightMax`, we can determine the water trapped at `arr[left]` because the left side is the limiting boundary.
Otherwise, we can determine the water trapped at `arr[right]` because the right side is the limiting boundary.
How does this work?
Let us consider the case when left max is less than the right max. For arr[left], we know left max for it and we also know that the right max for it would not be less than left max because we already have a greater value in arr[right...n-1]. So for the current bar, we can find the amount of water by finding the difference between the current bar and the left max bar.
C++
#include<iostream>#include<vector>usingnamespacestd;intmaxWater(vector<int>&arr){intleft=1;intright=arr.size()-2;// lMax : Maximum in subarray arr[0..left-1]// rMax : Maximum in subarray arr[right+1..n-1]intlMax=arr[left-1];intrMax=arr[right+1];intres=0;while(left<=right){// If rMax is smaller, then we can // decide the amount of water for arr[right]if(rMax<=lMax){// Add the water for arr[right]res+=max(0,rMax-arr[right]);// Update right maxrMax=max(rMax,arr[right]);// Update right pointer as we have // decided the amount of water for thisright-=1;}else{// Add the water for arr[left]res+=max(0,lMax-arr[left]);// Update left maxlMax=max(lMax,arr[left]);// Update left pointer as we have // decided water for thisleft+=1;}}returnres;}intmain(){vector<int>arr={2,1,5,3,1,0,4};cout<<maxWater(arr)<<endl;return0;}
C
#include<stdio.h>intmaxWater(intarr[],intn){intleft=1;intright=n-2;// lMax : Maximum in subarray arr[0..left-1]// rMax : Maximum in subarray arr[right+1..n-1]intlMax=arr[left-1];intrMax=arr[right+1];intres=0;while(left<=right){// If rMax is smaller, then we can// decide the amount of water for arr[right]if(rMax<=lMax){// Add the water for arr[right]res+=(rMax-arr[right])>0?(rMax-arr[right]):0;// Update right maxrMax=rMax>arr[right]?rMax:arr[right];// Update right pointer as we have // decided the amount of water for thisright-=1;}else{// Add the water for arr[left]res+=(lMax-arr[left])>0?(lMax-arr[left]):0;// Update left maxlMax=lMax>arr[left]?lMax:arr[left];// Update left pointer as we have decided water for thisleft+=1;}}returnres;}intmain(){intarr[]={2,1,5,3,1,0,4};intn=sizeof(arr)/sizeof(arr[0]);printf("%d\n",maxWater(arr,n));return0;}
Java
classGFG{staticintmaxWater(int[]arr){intleft=1;intright=arr.length-2;// lMax : Maximum in subarray arr[0..left-1]// rMax : Maximum in subarray arr[right+1..n-1]intlMax=arr[left-1];intrMax=arr[right+1];intres=0;while(left<=right){// If rMax is smaller, then we can decide// the amount of water for arr[right]if(rMax<=lMax){// Add the water for arr[right]res+=Math.max(0,rMax-arr[right]);// Update right maxrMax=Math.max(rMax,arr[right]);// Update right pointer as we have decided the amount of water for thisright-=1;}else{// Add the water for arr[left]res+=Math.max(0,lMax-arr[left]);// Update left maxlMax=Math.max(lMax,arr[left]);// Update left pointer as we have// decided water for thisleft+=1;}}returnres;}publicstaticvoidmain(String[]args){int[]arr={2,1,5,3,1,0,4};System.out.println(maxWater(arr));}}
Python
defmaxWater(arr):left=1right=len(arr)-2# lMax : Maximum in subarray arr[0..left-1]# rMax : Maximum in subarray arr[right+1..n-1]lMax=arr[left-1]rMax=arr[right+1]res=0whileleft<=right:# If rMax is smaller, then we can decide the # amount of water for arr[right]ifrMax<=lMax:# Add the water for arr[right]res+=max(0,rMax-arr[right])# Update right maxrMax=max(rMax,arr[right])# Update right pointer as we have decided # the amount of water for thisright-=1else:# Add the water for arr[left]res+=max(0,lMax-arr[left])# Update left maxlMax=max(lMax,arr[left])# Update left pointer as we have decided # the amount of water for thisleft+=1returnresif__name__=="__main__":arr=[2,1,5,3,1,0,4]print(maxWater(arr))
C#
usingSystem;classGFG{staticintmaxWater(int[]arr){intleft=1;intright=arr.Length-2;// lMax : Maximum in subarray arr[0..left-1]// rMax : Maximum in subarray arr[right+1..n-1]intlMax=arr[left-1];intrMax=arr[right+1];intres=0;while(left<=right){// If rMax is smaller, then we can decide the // amount of water for arr[right]if(rMax<=lMax){// Add the water for arr[right]res+=Math.Max(0,rMax-arr[right]);// Update right maxrMax=Math.Max(rMax,arr[right]);// Update right pointer as we have decided// the amount of water for thisright-=1;}else{// Add the water for arr[left]res+=Math.Max(0,lMax-arr[left]);// Update left maxlMax=Math.Max(lMax,arr[left]);// Update left pointer as we have decided// water for thisleft+=1;}}returnres;}staticvoidMain(){int[]arr={2,1,5,3,1,0,4};Console.WriteLine(maxWater(arr));}}
JavaScript
functionmaxWater(arr){letleft=1;letright=arr.length-2;// lMax : Maximum in subarray arr[0..left-1]// rMax : Maximum in subarray arr[right+1..n-1]letlMax=arr[left-1];letrMax=arr[right+1];letres=0;while(left<=right){// If rMax is smaller, then we can decide the // amount of water for arr[right]if(rMax<=lMax){// Add the water for arr[right]res+=Math.max(0,rMax-arr[right]);// Update right maxrMax=Math.max(rMax,arr[right]);// Update right pointer as we have decided // the amount of water for thisright-=1;}else{// Add the water for arr[left]res+=Math.max(0,lMax-arr[left]);// Update left maxlMax=Math.max(lMax,arr[left]);// Update left pointer as we have decided water for thisleft+=1;}}returnres;}// Driver codeletarr=[2,1,5,3,1,0,4];console.log(maxWater(arr));
Output
9
[Alternate Approach] Using Stack - O(n) Time and O(n) Space
This approach uses the Next Greater Element and Previous Greater Element concepts.
Use a stack to find the greater element on the left and right of each bar.
These greater elements act as boundaries that can hold water.
The water trapped at an index is determined by the shorter boundary: min(leftGreater, rightGreater) - height[i]
Repeat this process for all elements to calculate the total trapped water.
Using a stack helps us find these boundaries efficiently.
C++
#include<iostream>#include<vector>#include<stack>usingnamespacestd;intmaxWater(vector<int>&arr){stack<int>st;intres=0;for(inti=0;i<arr.size();i++){// Pop all items smaller than arr[i]while(!st.empty()&&arr[st.top()]<arr[i]){intpop_height=arr[st.top()];st.pop();if(st.empty())break;// arr[i] is the next greater for the removed item// and new stack top is the previous greater intdistance=i-st.top()-1;// Take the minimum of two heights (next and prev greater)// and find the amount of water that we can fill in all// bars between the twointwater=min(arr[st.top()],arr[i])-pop_height;res+=distance*water;}st.push(i);}returnres;}intmain(){vector<int>arr={2,1,5,3,1,0,4};cout<<maxWater(arr);return0;}
C
#include<stdio.h>#include<stdlib.h>structStack{int*array;inttop;intcapacity;};structStack*createStack(intcapacity){structStack*stack=(structStack*)malloc(sizeof(structStack));stack->capacity=capacity;stack->top=-1;stack->array=(int*)malloc(capacity*sizeof(int));returnstack;}// Stack is full when top is equal to the last indexintisFull(structStack*stack){returnstack->top==stack->capacity-1;}// Stack is empty when top is -1intisEmpty(structStack*stack){returnstack->top==-1;}// Function to add an item to stackvoidpush(structStack*stack,intitem){if(isFull(stack))return;stack->array[++stack->top]=item;}// Function to remove an item from stackintpop(structStack*stack){if(isEmpty(stack))return-1;returnstack->array[stack->top--];}// Function to return the top from the stack without poppinginttop(structStack*stack){returnstack->array[stack->top];}intmaxWater(int*arr,intn){structStack*st=createStack(n);intres=0;for(inti=0;i<n;i++){// Pop all items smaller than arr[i]while(!isEmpty(st)&&arr[top(st)]<arr[i]){intpop_height=arr[pop(st)];if(isEmpty(st))break;// arr[i] is the next greater for the removed item// and new stack top is the previous greater intdistance=i-top(st)-1;// Take the minimum of two heights (next and prev greater)intwater=(arr[top(st)]<arr[i])?arr[top(st)]:arr[i];// Find the amount of waterwater-=pop_height;res+=distance*water;}push(st,i);}free(st->array);free(st);returnres;}intmain(){intarr[]={2,1,5,3,1,0,4};intn=sizeof(arr)/sizeof(arr[0]);printf("%d\n",maxWater(arr,n));return0;}
Java
importjava.util.Stack;classGFG{staticintmaxWater(int[]arr){Stack<Integer>st=newStack<>();intres=0;for(inti=0;i<arr.length;i++){// Pop all items smaller than arr[i]while(!st.isEmpty()&&arr[st.peek()]<arr[i]){intpop_height=arr[st.pop()];if(st.isEmpty())break;// arr[i] is the next greater for the removed item// and new stack top is the previous greater intdistance=i-st.peek()-1;// Take the minimum of two heights (next and prev greater)intwater=Math.min(arr[st.peek()],arr[i]);// Find the amount of waterwater-=pop_height;res+=distance*water;}st.push(i);}returnres;}publicstaticvoidmain(String[]args){int[]arr={2,1,5,3,1,0,4};System.out.println(maxWater(arr));}}
Python
defmaxWater(arr):st=[]res=0foriinrange(len(arr)):# Pop all items smaller than arr[i]whilestandarr[st[-1]]<arr[i]:pop_height=arr[st.pop()]ifnotst:break# arr[i] is the next greater for the removed item# and new stack top is the previous greater distance=i-st[-1]-1# Take the minimum of two heights (next and prev greater)water=min(arr[st[-1]],arr[i])# Find the amount of waterwater-=pop_heightres+=distance*waterst.append(i)returnresif__name__=="__main__":arr=[2,1,5,3,1,0,4]print(maxWater(arr))
C#
usingSystem;usingSystem.Collections.Generic;classGFG{staticintmaxWater(int[]arr){Stack<int>st=newStack<int>();intres=0;for(inti=0;i<arr.Length;i++){// Pop all items smaller than arr[i]while(st.Count>0&&arr[st.Peek()]<arr[i]){intpop_height=arr[st.Pop()];if(st.Count==0)break;// arr[i] is the next greater for the removed item// and new stack top is the previous greater intdistance=i-st.Peek()-1;// Take the minimum of two heights (next and prev greater)intwater=Math.Min(arr[st.Peek()],arr[i]);// Find the amount of waterwater-=pop_height;res+=distance*water;}st.Push(i);}returnres;}staticvoidMain(){int[]arr={2,1,5,3,1,0,4};Console.WriteLine(maxWater(arr));}}
JavaScript
functionmaxWater(arr){letst=[];letres=0;for(leti=0;i<arr.length;i++){// Pop all items smaller than arr[i]while(st.length>0&&arr[st[st.length-1]]<arr[i]){letpop_height=arr[st.pop()];if(st.length===0)break;// arr[i] is the next greater for the removed item// and new stack top is the previous greater letdistance=i-st[st.length-1]-1;// Take the minimum of two heights (next and prev greater)letwater=Math.min(arr[st[st.length-1]],arr[i]);// Find the amount of waterwater-=pop_height;res+=distance*water;}st.push(i);}returnres;}// Driver Code letarr=[2,1,5,3,1,0,4];console.log(maxWater(arr));
You are visitor 01402605 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.