Pattern

Monotonic stack

Keep a stack whose values only increase or only decrease so you can find each element's next bigger or smaller neighbor in one pass.

What it is

A monotonic stack is a stack you maintain in sorted order (strictly increasing or strictly decreasing from bottom to top) by popping off any element that violates the order before pushing the new one. Whatever gets popped, at the moment it's popped, has just found the answer it was waiting for — the first larger or smaller value to its right — and whatever's left on the stack at the end is still waiting for one that never came. This turns an apparent O(n²) "compare everyone to everyone ahead of them" problem into a single O(n) pass, because each element is pushed and popped at most once.

When it applies

Tells in the problem

The classic mistake

Pushing values onto the stack instead of indices works fine until the problem needs the distance or width between two positions (how many days until the warmer one, how wide a histogram rectangle is) — at that point the value alone can't tell you where it was, and this is the mix-up interviewers report most often. This happens because the comparison logic only ever looks at values, so it's easy to forget that the answer being computed is almost always a function of position, not of the value itself. Guard against it by storing indices on the stack from the start and only dereferencing into the array when you need the actual value to compare.

Questions to start with

All 5 monotonic stack questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.