The “Trapping Rain Water” problem asks us to compute how much water can be trapped after raining, given an elevation map where the width of each bar is 1. The bars are represented as an array of non-negative integers.
Example:
[0,1,0,2,1,0,1,3,2,1,2,1]
6
This is a classic problem in array manipulation and precomputation. It introduces the concept of prefix maximums and suffix maximums, and also has an elegant two-pointer solution. It's a common technical interview question that tests both brute-force intuition and optimization with space/time trade-offs.
To calculate how much water can be trapped at each index, we must know the tallest bar to the left and to the right of it. The amount of water at index i
is the minimum of those two heights minus the height at i
itself.
max_left
and max_right
of the same length as the input array height
.max_left[i]
as the highest bar to the left of i
.max_right[i]
as the highest bar to the right of i
.i
, compute the trapped water as min(max_left[i], max_right[i]) - height[i]
.
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Time Complexity: O(n), where n
is the length of the height array. We traverse the array three times (left max, right max, compute water).
Space Complexity: O(n) for storing two auxiliary arrays max_left
and max_right
.
Instead of storing two full arrays, we can optimize space using two pointers and variables to track the current left and right maximum heights dynamically.
left = 0
and right = height.length - 1
.left_max
and right_max
as the maximum seen so far from each end.left < right
:
height[left] < height[right]
:
height[left] >= left_max
, update left_max
.left_max - height[left]
to total.left
forward.height[right] >= right_max
, update right_max
.right_max - height[right]
to total.right
backward.This results in O(n) time and O(1) space.
The “Trapping Rain Water” problem is an excellent demonstration of how precomputation or two-pointer strategies can optimize time and space complexity. It’s one of the most iconic examples of converting a seemingly brute-force problem into an elegant linear-time solution.