Monotonic stacks and deques
One structure answers every "nearest larger element" question in linear time, and the reason is a single invariant — the stack holds only the indices whose answer is still undecided, in sorted order, because an element with a bigger neighbour behind it can never be anyone's answer again; this lesson derives that invariant, uses it on the histogram problem, and then adds a left boundary to get the sliding-window maximum.
What you'll be able to do
- State the monotonic-stack invariant and explain why an element that is dominated can be discarded forever
- Derive next-greater-element and daily-temperatures from that invariant rather than recalling the code
- Solve largest-rectangle-in-histogram, explaining what is known at the moment a bar is popped
- Extend the idea to a monotonic deque for sliding-window maximum, and say why a plain stack is not enough
- Recognise the problem phrasings that signal a monotonic structure, and the ones that rule it out
Before this: stacks-and-queues, sliding-window
The rest of this lesson is in the app
One structure answers every "nearest larger element" question in linear time, and the reason is a single invariant — the stack holds only the indices whose answer is still undecided, in sorted order, because an element with a bigger neighbour behind it can never be anyone's answer again; this lesson derives that invariant, uses it on the histogram problem, and then adds a left boundary to get the sliding-window maximum. This walkthrough runs about 26 minutes, with runnable code you can edit and re-run as you read.
Continue in ChannelPulseThe first module of every track is free to read on the web — see what's open in Coding & data structures.