Imagine you're an architect designing a system to collect rainwater in a cityscape with varying building heights. You have an elevation map represented by an array of non-negative integers, where each integer represents the height of a building and each building has a uniform width of 1 unit.
After it rains, water gets trapped between the buildings, forming pools. Your task is to calculate the total amount of rainwater that can be trapped in this urban landscape.
Goal: Given an array of heights, return the total units of water that can be trapped.
Example: For heights [0,1,0,2,1,0,1,3,2,1,2,1], water gets trapped between buildings, and the total trapped water is 6 units.
Input & Output
Visualization
Time & Space Complexity
Three separate O(n) passes through the array
Two additional arrays to store left and right maximum heights
Constraints
- n == height.length
- 1 โค n โค 2 ร 104
- 0 โค height[i] โค 3 ร 104
- Follow-up: Can you solve it in O(1) extra space?