Maintain indices in increasing height order. When height[i] < height[stack.top()], pop and compute area = height × width (width = distance to previous smaller bar). A sentinel 0 at end flushes all remaining bars. O(n) — each bar pushed/popped once.
💡 Key insight: the stack always holds indices in strictly increasing height order. A smaller incoming bar acts as the "right boundary" for every taller bar being popped — giving us both height and width in O(1).
⚡ Complexity
Time
O(n)
Space
O(n)
Each index is pushed onto the stack exactly once and popped at most once — so total work is O(2n) = O(n) even with the inner while loop.
Sentinel 0 guarantees all bars are processed — no post-loop cleanup needed.