Back to Roadmap
Week 3Day 16 of 35

Monotonic Stack

Keep unresolved indexes in stack order so a new greater value can answer old questions immediately.

Day Progress0%

0 of 3 problems solved

Pattern Focus

Monotonic Stack

Keep unresolved indexes in stack order so a new greater value can answer old questions immediately.

Pattern Checklist
  • Am I waiting for the next greater value?
  • Should the stack store indexes so I can compute distance?
  • Do smaller temperatures get resolved when a warmer day appears?
🌡️New to DSA? Start here 🧠

Daily Temperatures is a waiting-room problem. Each day is asking, 'How long until someone warmer shows up?' A monotonic stack keeps days that are still waiting for better weather. When a hotter day arrives, it immediately answers old questions and kicks those colder days out of the stack.

The stack holds unresolved days, not the final answers.

How to think about it
  1. 1Store indexes in the stack so you can calculate day differences later.
  2. 2Move through temperatures from left to right.
  3. 3While the current day is warmer than the day on top of the stack, pop that older index and fill its answer.
  4. 4Push the current index when it is still waiting for a warmer day.
🚧Common Mistake

Storing temperatures instead of indexes makes it impossible to compute how many days someone waited.

🔍Problem Hints

Baseball Game

Simulate with a stack. '+' sums the top two, 'D' doubles the top, 'C' removes the top. Process each operation in order.

Maximal Rectangle

Treat each row as a base for a histogram using accumulated heights. Run Largest Rectangle in Histogram on each row's heights.

Problems

Daily Temperatures

medium

Baseball Game

easy

Maximal Rectangle

hard