42. Trapping Rain Water
hardAsked at BloombergCalculating trapped water between histogram bars maps directly onto Bloomberg's time-series gap analysis — measuring how much volume pools between market microstructure events — and rewards the two-pointer insight that eliminates extra passes.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
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.
Constraints
n == height.length1 <= n <= 2 * 10^40 <= height[i] <= 10^5
Examples
Example 1
height = [0,1,0,2,1,0,1,3,2,1,2,1]6Explanation: The elevation map traps 6 units of rainwater.
Example 2
height = [4,2,0,3,2,5]9Approaches
1. Precomputed prefix/suffix maxima
For each index, water trapped = min(maxLeft, maxRight) - height[i]. Precompute both arrays in two passes, then a third pass accumulates the total.
- Time
- O(n)
- Space
- O(n)
function trap(height) {
const n = height.length;
const maxL = new Array(n).fill(0);
const maxR = new Array(n).fill(0);
maxL[0] = height[0];
for (let i = 1; i < n; i++) maxL[i] = Math.max(maxL[i-1], height[i]);
maxR[n-1] = height[n-1];
for (let i = n-2; i >= 0; i--) maxR[i] = Math.max(maxR[i+1], height[i]);
let water = 0;
for (let i = 0; i < n; i++) water += Math.min(maxL[i], maxR[i]) - height[i];
return water;
}Tradeoff:
2. Two pointers (optimal)
Use left and right pointers converging inward. Whichever side has the smaller max boundary determines the trapped water at that index — no auxiliary arrays needed.
- Time
- O(n)
- Space
- O(1)
function trap(height) {
let left = 0, right = height.length - 1;
let maxL = 0, maxR = 0, water = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= maxL) maxL = height[left];
else water += maxL - height[left];
left++;
} else {
if (height[right] >= maxR) maxR = height[right];
else water += maxR - height[right];
right--;
}
}
return water;
}Tradeoff:
Bloomberg-specific tips
Bloomberg interviewers love this problem because the two-pointer solution demonstrates the same reasoning Bloomberg quants use for intraday liquidity windows — the side with the smaller maximum boundary is the binding constraint, so you process it first. Articulate that invariant clearly before writing a line of code; it signals you understand the why, not just the how.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Trapping Rain Water and other Bloomberg interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →