Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Examples:
Input: arr[] = {2, 0, 2}
Output: 2
Explanation:
The structure is like below
We can trap 2 units of water in the middle gap.
Input: arr[] = {3, 0, 2, 0, 4}
Output: 7
Explanation:
Structure is like below
We can trap "3 units" of water between 3 and 2,
"1 unit" on top of bar 2 and "3 units" between 2
and 4. See below diagram also.
Input: arr[] = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output: 6
Explanation:
The structure is like below
Trap "1 unit" between first 1 and 2, "4 units" between
first 2 and 3 and "1 unit" between second last 1 and last 2
We strongly recommend that you click here and practise it, before moving on to the solution.
Basic Insight:
An element of the array can store water if there are higher bars on left and right. The amount of water to be stored in every element can be found out by finding the heights of bars on the left and right sides. The idea is to compute the amount of water that can be stored in every element of the array.
Example
Consider the array {3, 0, 0, 2, 0, 4}, three units of water can be stored three indexes 1 and 2, and one unit of water at index 3, and three units of water at index 4.
For Array[] = {3, 0, 2, 0, 4}
Water stored = 0 + 3 + 1 + 3 + 0 = 7
Method 1: This is a simple solution to the above problem.
- Approach: The idea is to traverse every array element and find the highest bars on left and right sides. Take the smaller of two heights. The difference between the smaller height and height of the current element is the amount of water that can be stored in this array element.
- Algorithm:
- Traverse the array from start to end.
- For every element, traverse the array from start to that index and find the maximum height (a) and traverse the array from the current index to end and find the maximum height (b).
- The amount of water that will be stored in this column is min(a,b) – array[i], add this value to total amount of water stored
- Print the total amount of water stored.
-
Implementation:
C++
// C++ implementation of the approach#include<bits/stdc++.h>usingnamespacestd;// Function to return the maximum// water that can be storedintmaxWater(intarr[],intn){// To store the maximum water// that can be storedintres = 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++)left = max(left, arr[j]);// Find the maximum element on its rightintright = arr[i];for(intj=i+1; j<n; j++)right = max(right, arr[j]);// Update the maximum waterres = res + (min(left, right) - arr[i]);}returnres;}// Driver codeintmain(){intarr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};intn =sizeof(arr)/sizeof(arr[0]);cout << maxWater(arr, n);return0;}chevron_rightfilter_noneJava
// Java implementation of the approachclassGFG{// Function to return the maximum// water that can be storedpublicstaticintmaxWater(int[] arr,intn){// To store the maximum water// that can be storedintres =0;// For every element of the array// except first and last elementfor(inti =1; i < n -1; i++){// Find maximum element on its leftintleft = arr[i];for(intj =0; j < i; j++){left = Math.max(left, arr[j]);}// Find maximum element on its rightintright = arr[i];for(intj = i +1; j < n; j++){right = Math.max(right, arr[j]);}// Update maximum water valueres += Math.min(left, right) - arr[i];}returnres;}// Driver codepublicstaticvoidmain(String[] args){int[] arr = {0,1,0,2,1,0,1,3,2,1,2,1};intn = arr.length;System.out.print(maxWater(arr,n));}}// This code is contributed by Debidutta Rathchevron_rightfilter_nonePython3
# Python3 implementation of the approach# Function to return the maximum# water that can be storeddefmaxWater(arr, n) :# To store the maximum water# that can be storedres=0;# For every element of the arrayforiinrange(1, n-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, n) :right=max(right, arr[j]);# Update the maximum waterres=res+(min(left, right)-arr[i]);returnres;# Driver codeif__name__=="__main__":arr=[0,1,0,2,1,0,1,3,2,1,2,1];n=len(arr);print(maxWater(arr, n));# This code is contributed by AnkitRai01chevron_rightfilter_noneOutput:6
-
Complexity Analysis:
- Time Complexity: O(n2).
There are two nested loops traversing the array, So time Complexity is O(n2). - Space Complexity: O(1).
No extra space required.
- Time Complexity: O(n2).
Method 2: This is an efficient solution to the above problem.
- Approach: In the previous solution, to find the highest bar on the left and right, array traversal is needed which reduces the efficiency of the solution. To make this efficient one must pre-compute the highest bar on the left and right of every bar in linear time. Then use these pre-computed values to find the amount of water in every array element.
- Algorithm:
- Create two array left and right of size n. create a variable max_ = INT_MIN.
- Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = max_
- Update max_ = INT_MIN.
- Run another loop from end to start. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign right[i] = max_
- Traverse the array from start to end.
- The amount of water that will be stored in this column is min(a,b) – array[i],(where a = left[i] and b = right[i]) add this value to total amount of water stored
- Print the total amount of water stored.
-
Implementation:
C++
// C++ program to find maximum amount of water that can// be trapped within given set of bars.#include <bits/stdc++.h>usingnamespacestd;intfindWater(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 ith bar including itselfintright[n];// Initialize resultintwater = 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 element// consider the amount of water on i'th bar, the// amount of water accumulated on this particular// bar will be equal to min(left[i], right[i]) - arr[i] .for(inti = 0; i < n; i++)water += min(left[i], right[i]) - arr[i];returnwater;}// Driver programintmain(){intarr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };intn =sizeof(arr) /sizeof(arr[0]);cout <<"Maximum water that can be accumulated is "<< findWater(arr, n);return0;}chevron_rightfilter_noneJava
// Java program to find maximum amount of water that can// be trapped within given set of bars.classTest {staticintarr[] =newint[] {0,1,0,2,1,0,1,3,2,1,2,1};// Method for maximum amount of waterstaticintfindWater(intn){// left[i] contains height of tallest bar to the// left of i'th bar including itselfintleft[] =newint[n];// Right [i] contains height of tallest bar to// the right of ith bar including itselfintright[] =newint[n];// Initialize resultintwater =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 element// consider the amount of water on i'th bar, the// amount of water accumulated on this particular// bar will be equal to min(left[i], right[i]) - arr[i] .for(inti =0; i < n; i++)water += Math.min(left[i], right[i]) - arr[i];returnwater;}// Driver method to test the above functionpublicstaticvoidmain(String[] args){System.out.println("Maximum water that can be accumulated is "+ findWater(arr.length));}}chevron_rightfilter_nonePython3
# Python program to find maximum amount of water that can# be trapped within given set of bars.deffindWater(arr, n):# left[i] contains height of tallest bar to the# left of i'th bar including itselfleft=[0]*n# Right [i] contains height of tallest bar to# the right of ith bar including itselfright=[0]*n# Initialize resultwater=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 element# consider the amount of water on i'th bar, the# amount of water accumulated on this particular# bar will be equal to min(left[i], right[i]) - arr[i] .foriinrange(0, n):water+=min(left[i], right[i])-arr[i]returnwater# Driver programarr=[0,1,0,2,1,0,1,3,2,1,2,1]n=len(arr)print("Maximum water that can be accumulated is", findWater(arr, n))# This code is contributed by# Smitha Dinesh Semwalchevron_rightfilter_noneC#
// C# program to find maximum amount of water that can// be trapped within given set of bars.usingSystem;classTest {staticint[] arr =newint[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };// Method for maximum amount of waterstaticintfindWater(intn){// left[i] contains height of tallest bar to the// left of i'th bar including itselfint[] left =newint[n];// Right [i] contains height of tallest bar to// the right of ith bar including itselfint[] right =newint[n];// Initialize resultintwater = 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 element// consider the amount of water on i'th bar, the// amount of water accumulated on this particular// bar will be equal to min(left[i], right[i]) - arr[i] .for(inti = 0; i < n; i++)water += Math.Min(left[i], right[i]) - arr[i];returnwater;}// Driver method to test the above functionpublicstaticvoidMain(){Console.WriteLine("Maximum water that can be accumulated is "+ findWater(arr.Length));}}// This code is contributed by vt_m.chevron_rightfilter_nonePHP
<?php// PHP program to find maximum// amount of water that can// be trapped within given set of bars.functionfindWater($arr,$n){// left[i] contains height of// tallest bar to the// left of i'th bar including// itself// Right [i] contains height// of tallest bar to the right// of ith bar including itself// $right[$n];// Initialize result$water= 0;// Fill left array$left[0] =$arr[0];for($i= 1;$i<$n;$i++)$left[$i] = max($left[$i- 1],$arr[$i]);// Fill right array$right[$n- 1] =$arr[$n- 1];for($i=$n- 2;$i>= 0;$i--)$right[$i] = max($right[$i+ 1],$arr[$i]);// Calculate the accumulated// water element by element// consider the amount of// water on i'th bar, the// amount of water accumulated// on this particular// bar will be equal to min(left[i],// right[i]) - arr[i] .for($i= 0;$i<$n;$i++)$water+= min($left[$i],$right[$i])-$arr[$i];return$water;}// Driver program$arr=array(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1);$n= sizeof($arr);echo"Maximum water that can be accumulated is ",findWater($arr,$n);// This code is contributed by ajit?>chevron_rightfilter_none
Output:Maximum water that can be accumulated is 6
-
Complexity Analysis:
- Time Complexity: O(n).
Only one traversal of the array is needed, So time Complexity is O(n). - Space Complexity: O(n).
Two extra array is needed each of size n.
- Time Complexity: O(n).
- Space Optimization for above Solution: Instead of maintaing two arrays of size n for storing left and right max of each element, maintain two variables to store the maximum till that point. Since water trapped at any element = min(max_left, max_right) – arr[i]. Calculate water trapped on smaller element out of A[lo] and A[hi] first and move the pointers till lo doesn’t cross hi.
-
Implementation:
C++
// C++ program to find maximum amount of water that can// be trapped within given set of bars.// Space Complexity : O(1)#include <iostream>usingnamespacestd;intfindWater(intarr[],intn){// initialize outputintresult = 0;// maximum element on left and rightintleft_max = 0, right_max = 0;// indices to traverse the arrayintlo = 0, hi = n - 1;while(lo <= hi) {if(arr[lo] < arr[hi]) {if(arr[lo] > left_max)// update max in leftleft_max = arr[lo];else// water on curr element = max - currresult += left_max - arr[lo];lo++;}else{if(arr[hi] > right_max)// update right maximumright_max = arr[hi];elseresult += right_max - arr[hi];hi--;}}returnresult;}intmain(){intarr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };intn =sizeof(arr) /sizeof(arr[0]);cout <<"Maximum water that can be accumulated is "<< findWater(arr, n);}// This code is contributed by Aditi Sharmachevron_rightfilter_noneJava
// JAVA Code For Trapping Rain Waterimportjava.util.*;classGFG {staticintfindWater(intarr[],intn){// initialize outputintresult =0;// maximum element on left and rightintleft_max =0, right_max =0;// indices to traverse the arrayintlo =0, hi = n -1;while(lo <= hi) {if(arr[lo] < arr[hi]) {if(arr[lo] > left_max)// update max in leftleft_max = arr[lo];else// water on curr element =// max - currresult += left_max - arr[lo];lo++;}else{if(arr[hi] > right_max)// update right maximumright_max = arr[hi];elseresult += right_max - arr[hi];hi--;}}returnresult;}/* Driver program to test above function */publicstaticvoidmain(String[] args){intarr[] = {0,1,0,2,1,0,1,3,2,1,2,1};intn = arr.length;System.out.println("Maximum water that "+"can be accumulated is "+ findWater(arr, n));}}// This code is contributed by Arnav Kr. Mandal.chevron_rightfilter_nonePython3
# Python program to find# maximum amount of water that can# be trapped within given set of bars.# Space Complexity : O(1)deffindWater(arr, n):# initialize outputresult=0# maximum element on left and rightleft_max=0right_max=0# indices to traverse the arraylo=0hi=n-1while(lo <=hi):if(arr[lo] < arr[hi]):if(arr[lo] > left_max):# update max in leftleft_max=arr[lo]else:# water on curr element = max - currresult+=left_max-arr[lo]lo+=1else:if(arr[hi] > right_max):# update right maximumright_max=arr[hi]else:result+=right_max-arr[hi]hi-=1returnresult# Driver programarr=[0,1,0,2,1,0,1,3,2,1,2,1]n=len(arr)print("Maximum water that can be accumulated is ",findWater(arr, n))# This code is contributed# by Anant Agarwal.chevron_rightfilter_noneC#
// C# Code For Trapping Rain WaterusingSystem;classGFG {staticintfindWater(int[] arr,intn){// initialize outputintresult = 0;// maximum element on left and rightintleft_max = 0, right_max = 0;// indices to traverse the arrayintlo = 0, hi = n - 1;while(lo <= hi) {if(arr[lo] < arr[hi]) {if(arr[lo] > left_max)// update max in leftleft_max = arr[lo];else// water on curr element =// max - currresult += left_max - arr[lo];lo++;}else{if(arr[hi] > right_max)// update right maximumright_max = arr[hi];elseresult += right_max - arr[hi];hi--;}}returnresult;}// Driver programpublicstaticvoidMain(){int[] arr = { 0, 1, 0, 2, 1, 0, 1,3, 2, 1, 2, 1 };intresult = Trap.findWater(arr, arr.length);System.out.print(" Total trapping water: "+ result);}}// This code is contributed by vt_m.chevron_rightfilter_nonePHP
<?php// PHP program to find maximum amount// of water that can be trapped within// given set of bars.// Method to find maximum amount// of water that can be trapped within// given set of bars.functionfindWater($arr,$n){// initialize output$result= 0;// maximum element on// left and right$left_max= 0;$right_max= 0;// indices to traverse// the array$lo= 0;$hi=$n- 1;while($lo<=$hi){if($arr[$lo] <$arr[$hi]){if($arr[$lo] >$left_max)// update max in left$left_max=$arr[$lo];else// water on curr// element = max - curr$result+=$left_max-$arr[$lo];$lo++;}else{if($arr[$hi] >$right_max)// update right maximum$right_max=$arr[$hi];else$result+=$right_max-$arr[$hi];$hi--;}}return$result;}// Driver Code$arr=array(0, 1, 0, 2, 1, 0,1, 3, 2, 1, 2, 1);$n=count($arr);echo"Maximum water that can be accumulated is ", findWater($arr,$n);// This code is contributed by anuj_67.?>chevron_rightfilter_none
Output:Maximum water that can be accumulated is 6
-
Complexity Analysis:
- Time Complexity: O(n).
Only one traversal of the array is needed. - Auxiliary Space: O(1).
As no extra space is required.
- Time Complexity: O(n).
- Thanks to Gaurav Ahirwar and Aditi Sharma for above solution.
Method 3:Here another efficient solution has been shown.
- Approach : The concept here is that if there is a larger wall to the right then the water can be retained with height equal to the smaller wall on the left. If there are no larger walls to the right then start from the left. There must be a larger wall to the left now. Let’s take an example if the heights are {….,3, 2, 1, 4,….}, So here 3 and 4 are boundaries the heights 2 and 1 are submerged and cannot act as boundaries. So at any point or index knowing the previous boundary is sufficient if there is a higher or equal length boundary in the remaining part of the array. If not then traverse the array backwards and now must be a larger wall to the left.
- Algorithm :
- Loop from index 0 to the end of the given array.
- If a wall greater than or equal to the previous wall is encountered then make note of the index of that wall in a var called prev_index.
- Keep adding previous wall’s height minus the current (ith) wall to the variable water.
- Have a temporary variable that stores the same value as water.
- If no wall greater than or equal to the previous wall is found then quit.
- If prev_index < size of the input array then subtract the temp variable from water, and loop from end of the input array to prev_index and find a wall greater than or equal to the previous wall (in this case, the last wall from backwards).
-
Implementation:
C++
// C++ implementation of the approach#include<iostream>usingnamespacestd;// Function to return the maximum// water that can be storedintmaxWater(intarr[],intn){intsize = n - 1;// Let the first element be stored as// previous, we shall loop from index 1intprev = arr[0];// To store previous wall's indexintprev_index = 0;intwater = 0;// To store the water until a larger wall// is found, if there are no larger walls// then delete temp value from waterinttemp = 0;for(inti = 1; i <= size; i++){// If the current wall is taller than// the previous wall then make current// wall as the previous wall and its// index as previous wall's index// for the subsequent loopsif(arr[i] >= prev){prev = arr[i];prev_index = i;// Because larger or same// height wall is foundtemp = 0;}else{// Since current wall is shorter than// the previous, we subtract previous// wall's height from the current wall's// height and add it to the waterwater += prev - arr[i];// Store the same value in temp as well// If we dont find any larger wall then// we will subtract temp from watertemp += prev - arr[i];}}// If the last wall was larger than or equal// to the previous wall then prev_index would// be equal to size of the array (last element)// If we didn't find a wall greater than or equal// to the previous wall from the left then// prev_index must be less than the index// of the last elementif(prev_index < size){// Temp would've stored the water collected// from previous largest wall till the end// of array if no larger wall was found then// it has excess water and remove that// from water variablewater -= temp;// We start from the end of the array,// so previous should be assigned to// the last elementprev = arr[size];// Loop from the end of array up to the// previous index which would contain// the largest wall from the leftfor(inti = size; i >= prev_index; i--){// Right end wall will be definitely// smaller than the 'previous index' wallif(arr[i] >= prev){prev = arr[i];}else{water += prev - arr[i];}}}// Return the maximum waterreturnwater;}// Driver Codeintmain(){intarr[] = { 0, 1, 0, 2, 1, 0,1, 3, 2, 1, 2, 1 };intn =sizeof(arr) /sizeof(arr[0]);cout << maxWater(arr, n);return0;}// This code is contributed by Debidutta Rathchevron_rightfilter_noneJava
// Java implementation of the approachclassGFG {// Function to return the maximum// water that can be storedpublicstaticintmaxWater(intarr[],intn){intsize = n -1;// Let the first element be stored as// previous, we shall loop from index 1intprev = arr[0];// To store previous wall's indexintprev_index =0;intwater =0;// To store the water until a larger wall// is found, if there are no larger walls// then delete temp value from waterinttemp =0;for(inti =1; i <= size; i++) {// If the current wall is taller than// the previous wall then make current// wall as the previous wall and its// index as previous wall's index// for the subsequent loopsif(arr[i] >= prev) {prev = arr[i];prev_index = i;// Because larger or same height wall is foundtemp =0;}else{// Since current wall is shorter than// the previous, we subtract previous// wall's height from the current wall's// height and add it to the waterwater += prev - arr[i];// Store the same value in temp as well// If we dont find any larger wall then// we will subtract temp from watertemp += prev - arr[i];}}// If the last wall was larger than or equal// to the previous wall then prev_index would// be equal to size of the array (last element)// If we didn't find a wall greater than or equal// to the previous wall from the left then// prev_index must be less than the index// of the last elementif(prev_index < size) {// Temp would've stored the water collected// from previous largest wall till the end// of array if no larger wall was found then// it has excess water and remove that// from 'water' varwater -= temp;// We start from the end of the array, so previous// should be assigned to the last elementprev = arr[size];// Loop from the end of array up to the 'previous index'// which would contain the "largest wall from the left"for(inti = size; i >= prev_index; i--) {// Right end wall will be definitely smaller// than the 'previous index' wallif(arr[i] >= prev) {prev = arr[i];}else{water += prev - arr[i];}}}// Return the maximum waterreturnwater;}// Driver codepublicstaticvoidmain(String[] args){intarr[] = {0,1,0,2,1,0,1,3,2,1,2,1};intn = arr.length;System.out.print(maxWater(arr, n));}}chevron_rightfilter_nonePython3
# Pythpn3 implementation of the approach# Function to return the maximum# water that can be storeddefmaxWater(arr, n):size=n-1# Let the first element be stored as# previous, we shall loop from index 1prev=arr[0]# To store previous wall's indexprev_index=0water=0# To store the water until a larger wall# is found, if there are no larger walls# then delete temp value from watertemp=0foriinrange(1, size+1):# If the current wall is taller than# the previous wall then make current# wall as the previous wall and its# index as previous wall's index# for the subsequent loopsif(arr[i] >=prev):prev=arr[i]prev_index=i# Because larger or same height wall is foundtemp=0else:# Since current wall is shorter than# the previous, we subtract previous# wall's height from the current wall's# height and add it to the waterwater+=prev-arr[i]# Store the same value in temp as well# If we dont find any larger wall then# we will subtract temp from watertemp+=prev-arr[i]# If the last wall was larger than or equal# to the previous wall then prev_index would# be equal to size of the array (last element)# If we didn't find a wall greater than or equal# to the previous wall from the left then# prev_index must be less than the index# of the last elementif(prev_index < size):# Temp would've stored the water collected# from previous largest wall till the end# of array if no larger wall was found then# it has excess water and remove that# from 'water' varwater-=temp# We start from the end of the array, so previous# should be assigned to the last elementprev=arr[size]# Loop from the end of array up to the 'previous index'# which would contain the "largest wall from the left"foriinrange(size, prev_index-1,-1):# Right end wall will be definitely smaller# than the 'previous index' wallif(arr[i] >=prev):prev=arr[i]else:water+=prev-arr[i]# Return the maximum waterreturnwater# Driver codearr=[0,1,0,2,1,0,1,3,2,1,2,1]n=len(arr)print(maxWater(arr, n))# This code is contributed by Mohit Kumarchevron_rightfilter_noneOutput:6
-
Complexity Analysis:
- Time Complexity: O(n).
As only one traversal of the array is needed. - Auxiliary Space: O(1).
As no extra space is required.
- Time Complexity: O(n).
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- The Two Water Jug Puzzle
- Maximum water that can be stored between two buildings
- Maximum litres of water that can be bought with N Rupees
- Program to find amount of water in a given glass
- Amazon ACMS Interview Experience
- Detect Cycle in a 2D grid
- Check if Array forms an increasing-decreasing sequence or vice versa
- Count of index pairs with equal elements in an array | Set 2
- Check if an Array can be Sorted by picking only the corner Array elements
- Sort an Array of Version Numbers
- Minimum Sum of Euclidean Distances to all given Points
- Median of difference of all pairs from an Array
- Maximize the last Array element as per the given conditions
- Find the point on X-axis from given N points having least Sum of Distances from all other points


