Taro Logo

Trapping Rain Water

Hard
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+49
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
3.6K views
Topics:
ArraysTwo PointersDynamic ProgrammingStacks

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input array is empty, null, or has fewer than 3 bars?
  2. Are the values in the elevation map guaranteed to be non-negative integers, or could we receive floating-point numbers or negative values?
  3. Can I assume the width of every elevation bar is uniformly 1, or could widths vary in the input?
  4. Is there a maximum memory limit I should be mindful of, or can I allocate additional space for auxiliary data structures?
  5. Should I handle extremely large elevation values that might cause integer overflow when summing the total trapped water?

Brute Force Solution

Approach

Imagine looking at a street of buildings of different heights after it has rained, and you want to figure out how much water gets trapped in the dips between them. The brute force approach looks at every single spot individually to see how much water can sit directly above it.

Here's how the algorithm would work step-by-step:

  1. Stand at the very first building and look at all the buildings to your left and all the buildings to your right.
  2. Find the tallest building on your left side and the tallest building on your right side.
  3. Determine which of those two tallest buildings is shorter, because water would spill over the shorter side.
  4. Calculate how much water can sit right above your current spot by seeing how much lower your current spot is compared to that shorter bounding height.
  5. Write down that amount of water.
  6. Take one step over to the next building and repeat the entire process of scanning left and right for the tallest buildings.
  7. Do this for every single building in the row, one by one.
  8. Add up all the trapped water amounts you found at each spot to get the final total.

Code Implementation

def trap(height_list):
    total_water = 0
    
    # Iterate through every building to calculate trapped water individually at each specific position
    for current_index in range(len(height_list)):
        max_left_height = 0
        max_right_height = 0
        
        for left_scanner in range(current_index, -1, -1):
            if height_list[left_scanner] > max_left_height:
                max_left_height = height_list[left_scanner]
                
        for right_scanner in range(current_index, len(height_list)):
            if height_list[right_scanner] > max_right_height:
                max_right_height = height_list[right_scanner]
                
        # Water overflows past the shorter bounding wall, so we must find the limiting boundary height
        limiting_boundary = min(max_left_height, max_right_height)
        
        if limiting_boundary > height_list[current_index]:
            # Accumulate water volume by subtracting the current building height from the bounding height
            total_water += limiting_boundary - height_list[current_index]
            
    return total_water

Big(O) Analysis

Time Complexity
O(n²) – For each of the n buildings in the array, we must scan all the buildings to its left and right to find the maximum heights. For the first building we scan nearly n elements, for the second we do the same, resulting in an operation count proportional to n * n. This totals approximately n² operations, which simplifies to the final Big O time complexity of O(n²).
Space Complexity
O(1) – The plain English explanation describes scanning left and right for the tallest buildings at every single spot without using any extra data structures. We only need a few primitive variables to keep track of the current building position, maximum heights, and the running total of trapped water. Because no temporary lists, hash maps, or recursive call stacks are utilized regardless of the input scale, the auxiliary memory remains completely constant. Therefore, the space complexity evaluates to O(1) as the input size N grows.

Optimal Solution

Approach

Instead of checking every puddle one by one, the optimal strategy uses two boundary markers moving from the outer edges toward the center. By always moving the shorter boundary inward, we can instantly know how much water a spot can hold without needing to look all the way across the entire landscape.

Here's how the algorithm would work step-by-step:

  1. Place one marker at the very beginning of the landscape and another marker at the very end.
  2. Keep track of the tallest height seen so far from the left side, and the tallest height seen so far from the right side.
  3. Compare the heights of the two boundary markers to see which side is currently shorter.
  4. Take the shorter side and move its marker one step closer to the center.
  5. At this new position, check if it is taller than the current tallest height for that side. If it is taller, update the tallest height; if it is shorter, calculate how much water collects in the space above it based on the current tallest height.
  6. Repeat the process of moving the shorter side inward and calculating trapped water until the two markers finally meet in the middle.
  7. By always letting the smaller side dictate the water level and moving inward, you efficiently calculate all the trapped water in a single sweep.

Code Implementation

def trap(height_landscape):
    if not height_landscape:
        return 0

    left_marker = 0
    right_marker = len(height_landscape) - 1
    tallest_left = 0
    tallest_right = 0
    accumulated_water = 0

    # The pointer with the smaller height limits the trapped water level.
    while left_marker < right_marker:
        if height_landscape[left_marker] < height_landscape[right_marker]:
            if height_landscape[left_marker] >= tallest_left:
                tallest_left = height_landscape[left_marker]
            else:
                accumulated_water += tallest_left - height_landscape[left_marker]

            left_marker += 1
        else:
            if height_landscape[right_marker] >= tallest_right:
                tallest_right = height_landscape[right_marker]
            else:
                accumulated_water += tallest_right - height_landscape[right_marker]

            right_marker -= 1

    return accumulated_water

Big(O) Analysis

Time Complexity
O(n) – The algorithm uses two pointers starting at opposite ends of the input array of size n, moving inward toward the center until they meet. During each step, we evaluate and move one pointer, performing constant time comparisons and water calculations. Since each element in the array is visited at most once, the total operations scale linearly as the pointers traverse the entire width of the landscape. This results in approximately n operations in a single pass, which simplifies to Big O of n.
Space Complexity
O(1) – The algorithm relies entirely on a fixed number of scalar variables to maintain the left and right markers, running maximum heights, and the cumulative water total, without allocating any auxiliary data structures that scale with the input size N. Because no temporary arrays, hash maps, or recursive call stacks are utilized, the extra memory consumption remains completely constant regardless of the length of the landscape. Therefore, the auxiliary space complexity simplifies to O(1) as the input size grows.

Edge Cases

Empty array or null input
How to Handle:
Return zero immediately as no water can be trapped without any elevation bars.
Arrays with fewer than 3 elements
How to Handle:
Return zero because at least three bars are required to form a depression that holds water.
Monotonically increasing or decreasing arrays
How to Handle:
Return zero since water will simply spill off the edges without any enclosed basin.
Arrays with all identical non-zero heights
How to Handle:
Return zero because flat terrain lacks the varying heights needed to form traps.
Massive inputs with millions of elements
How to Handle:
Use an O(n) time and O(1) space two-pointer approach to avoid memory and time limits.
Extremely tall elevation values
How to Handle:
Use 64-bit integer types to prevent arithmetic overflow when accumulating large water volumes.
Inputs containing zero-height bars
How to Handle:
Process them normally as valley floors that contribute directly to the trapped water volume.
Arrays with a single deep basin in the center
How to Handle:
The two-pointer technique naturally converges on the maximum height and accumulates the correct trapped volume.
0/75 completed