Trapping Rain Water

Calculate how much water can be trapped after raining given elevation heights.

Hard

Examples

Example 1: [0,1,0,2,1,0,1,3,2,1,2,1] → 6
Example 2: [3,0,2,0,4] → 7

Implementation

Ruby

    # 🌧️ Trapping Rain Water - Hard Two Pointer Problem
    #
    # Problem Statement:
    #   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.
    #
    # Input Examples:
    #   trap([0,1,0,2,1,0,1,3,2,1,2,1]) => 6
    #   trap([3,0,2,0,4]) => 7
    #
    # Algorithm: Two Pointers with Max Heights
    # - Use left and right pointers moving towards center
    # - Track left_max and right_max seen so far
    # - Water trapped at position = min(left_max, right_max) - current_height
    # - Move pointer with smaller max height (bottleneck determines water level)
    #
    # Time Complexity: O(n)
    # Space Complexity: O(1)
    def trap(height)
      return 0 if height.empty? || height.length < 3
      
      left = 0
      right = height.length - 1
      left_max = 0
      right_max = 0
      water_trapped = 0
      
      puts "Starting trap calculation for heights: #{height.inspect}"
      puts "Array length: #{height.length}"
      
      while left < right
        if height[left] < height[right]
          # Process left side (left side is the bottleneck)
          if height[left] >= left_max
            left_max = height[left]
            puts "Left #{left}: New left_max = #{left_max}, no water trapped"
          else
            water = left_max - height[left]
            water_trapped += water
            puts "Left #{left}: height=#{height[left]}, left_max=#{left_max}, water=#{water}, total=#{water_trapped}"
          end
          left += 1
        else
          # Process right side (right side is the bottleneck)
          if height[right] >= right_max
            right_max = height[right]
            puts "Right #{right}: New right_max = #{right_max}, no water trapped"
          else
            water = right_max - height[right]
            water_trapped += water
            puts "Right #{right}: height=#{height[right]}, right_max=#{right_max}, water=#{water}, total=#{water_trapped}"
          end
          right -= 1
        end
        
        puts "  Pointers: left=#{left}, right=#{right}, left_max=#{left_max}, right_max=#{right_max}"
      end
      
      puts "🌧️  Total water trapped: #{water_trapped}"
      water_trapped

Complexity Analysis

Time Complexity:
O(n)?
Why O(n)?
Single pass with two pointers moving towards center
We visit each element exactly once. Each position is processed when either left or right pointer reaches it.
Example: Array of 12 elements needs exactly 12 operations (6 from each pointer)
Space Complexity:
O(1)?
Why O(1)?
Only using a few variables regardless of input size
We only store left_max, right_max, and two pointers - constant space that doesn't grow with input.
Example: Same memory usage for array of 10 or 10,000 elements

Patterns & Techniques

Problem Details

Category: Pointer And Sliding Window
Difficulty: Hard
Module: PointerAndSlidingWindow
Method: trap
← Back to Pointer And Sliding Window