Horizontal Slicing
The Two Pointer method calculates water vertically column by column. The Stack method calculates water horizontally, slice by slice, as it identifies bowl shapes.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Calculate how much rain water can be trapped between elevation blocks. While often solved with Two Pointers, the Monotonic Stack solution elegantly calculates horizontal slices of water.
The Two Pointer method calculates water vertically column by column. The Stack method calculates water horizontally, slice by slice, as it identifies bowl shapes.
We keep a monotonically decreasing stack. As long as bars are going down, no water is trapped. We just push them to the stack, forming the left slope of a bowl.
When we encounter a bar taller than the top of the stack, we found the right wall of a bowl! We pop the bottom, look at the new top (the left wall), and calculate the trapped rectangular slice.