Prerequisites

What you need first

Complete Stack Patterns first. Monotonic stacks maintain elements in sorted order (increasing or decreasing), which enables efficient "next greater/smaller element" queries.

The key pattern: when a new element violates the monotonic property, pop elements until the property is restored. Each element is pushed and popped at most once, giving O(n)O(n) total.