Trapping rainwater problem: Find the maximum amount of water that can be trapped within a given set of bars where each bar’s width is 1 unit.

For example,

 
Input: An array containing height of bars {7, 0, 4, 2, 5, 0, 6, 4, 0, 5}

Trapping Rain Water bars

The maximum amount of water that can be trapped is 25, as shown below (blue).

Trapping Rain Water

Practice this problem

 
The idea is to calculate the maximum height bar on the left and right of every bar. The amount of water stored on top of each bar is equal to the minimum among the leading’ bar to the left and right minus the current bar’s height. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

The maximum amount of water that can be trapped is 25

Java


Download  Run Code

Output:

The maximum amount of water that can be trapped is 25

Python


Download  Run Code

Output:

The maximum amount of water that can be trapped is 25

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the total number of given bars.

Constant space solution

The O(1) space solution can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The maximum amount of water that can be trapped is 25

Java


Download  Run Code

Output:

The maximum amount of water that can be trapped is 25

Python


Download  Run Code

Output:

The maximum amount of water that can be trapped is 25

The time complexity of the above solution is O(n) and doesn’t require any extra space.