Stacks, Queues & Monotonicity
Two structures defined by the order things come back out, which turn out to solve matching, “next bigger” and sliding-range problems elegantly.
After this lesson you will be able to
- Explain stack (last in, first out) and queue (first in, first out) and pick the right one.
- Use Python's list as a stack and
collections.dequeas a queue and deque, at O(1) per operation. - Solve matching problems (brackets) with a stack.
- Explain and write the monotonic stack that finds “next greater element” in O(n).
- Use a monotonic deque to maintain a window maximum in O(n).
Before you start. Lists and loops are enough. Complexity basics help with the O(n²) versus O(n) comparison.