Coding & data structures · Linear structures — lists, stacks, queues, and intervals

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.

26 min read Full lesson in the app Patterns: monotonic stack, nearest greater element, monotonic deque, sentinel flush

What you'll be able to do

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 ChannelPulse

The first module of every track is free to read on the web — see what's open in Coding & data structures.