24. Trapping Rain Water
hardAsked at AdyenGiven an elevation map, compute how much water it traps after raining.
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]6Example 2
height = [4,2,0,3,2,5]9Approaches
1. Precompute left/right max
Two passes for the tallest wall to each side, then sum the gap above each bar.
- Time
- O(n)
- Space
- O(n)
const n = height.length;
const L = new Array(n), R = new Array(n);
L[0] = height[0]; for (let i = 1; i < n; i++) L[i] = Math.max(L[i-1], height[i]);
R[n-1] = height[n-1]; for (let i = n-2; i >= 0; i--) R[i] = Math.max(R[i+1], height[i]);
let total = 0;
for (let i = 0; i < n; i++) total += Math.min(L[i], R[i]) - height[i];
return total;Tradeoff:
2. Two-pointer O(1) space
Move from the lower side and accumulate against its own running max.
- Time
- O(n)
- Space
- O(1)
function trap(h) {
let l = 0, r = h.length - 1, lMax = 0, rMax = 0, total = 0;
while (l < r) {
if (h[l] < h[r]) {
lMax = Math.max(lMax, h[l]);
total += lMax - h[l];
l++;
} else {
rMax = Math.max(rMax, h[r]);
total += rMax - h[r];
r--;
}
}
return total;
}Tradeoff:
Adyen-specific tips
Adyen graders favor the two-pointer O(1)-space variant — they routinely benchmark fraud-score reservoir calcs and prize constant-space passes.
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 Adyen interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →