Data Structures19 sections · 729 units
Open in Course

Trapping Water - Stack Approach

Layer by layer

Use a monotonic decreasing stack. When you encounter a bar taller than the stack top:

1.1. Pop the top (the popped element forms a valley)

2.2. If stack is now empty, no water can be trapped

3.3. Otherwise, calculate water between current bar, popped bar, and new top

The water at this layer has width (istack.top()1)(i - stack.top() - 1) and height min(current,newTop)popped\min(current, newTop) - popped. Accumulate water as you pop.