Total Water Trapped Between Warehouse Rack Heights After a Leak
Last updated: November 29, 2026
Quick Overview
A roof leak floods a row of warehouse racks with heights given as an array of non-negative integers, each one unit wide. Compute how many units of water are trapped between the racks, in O(n) time and O(1) extra space.
Amazon
November 29, 20260
0
0 solved
A roof leak floods a row of warehouse racks with heights given as an array of non-negative integers, each one unit wide. Compute how many units of water are trapped between the racks, in O(n) time and O(1) extra space.
A classic Amazon onsite problem dressed in a facilities scenario. The interviewer checks that you derive the water above each index as min(max left, max right) minus height, then improve from prefix arrays to the two-pointer method with a clear invariant.
What the Interviewer Expects
- State the per-index formula
- Give the O(n) space prefix and suffix max version
- Optimize to two pointers with O(1) space
- Explain the invariant that justifies moving the smaller side
- Handle arrays shorter than three
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you solve the 2D version where racks form a height grid?
- How would you report water per gap between tall racks?
- What if heights update and you must recompute quickly?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Heights: list of non-negative ints, possibly empty. Return total trapped units as an int....
High-Level Design
Water at i is min(maxLeft[i], maxRight[i]) - h[i]. Prefix and suffix max arrays give O(n) time, O(n) space.
Two pointers: keep left, right, left_max, right_max. If h[left] < h[right], the...