Stacks in Python
Chapter 39: Stacks
5 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Last in, first out: push, pop and peek
A stack is a collection you only touch at one end, the top: the last item in is the first item out (LIFO, last in, first out).
Matching brackets and evaluating expressions
Brackets are balanced when every closer matches the most recent opener that is still open, and nothing is left open at the end; a stack of the open brackets checks exactly that.
The monotonic stack: the next greater element
Keep a stack of the positions still waiting for a bigger number; when a number arrives, pop every waiting position with a smaller number (this number is their answer), then push the new position.
Stack patterns: daily temperatures and stock span
Whenever a question asks for the next or previous bigger (or smaller) item, or how far it is, keep a monotonic stack of positions and let each pop answer one of them.
The largest rectangle in a histogram
The best rectangle uses the full height of some bar and stretches left and right until a shorter bar; a stack of indexes with rising heights finds both edges, because when a shorter bar arrives it pops every taller bar, and for a popped bar the shorter bar is its right edge and the bar now below it in the stack is just past its left edge.