Skip to the solution
MediumDSA9 min read

What is a monotonic stack and when do you use it?

786 views

The problem

Question presented to candidate: "What is a monotonic stack? Explain it, tell me which kinds of problems it solves, and code a Python example such as next greater element, explaining why it is O(n)."

What a strong answer should cover:

  • A stack kept sorted (increasing or decreasing) by popping before each push; popped elements get their answer from the new element.
  • The four variants: next or previous, greater or smaller, and how strict versus non-strict comparison handles duplicates.
  • O(n) time because each index is pushed once and popped at most once, despite the nested loop.
  • Recognising the pattern: nearest greater or smaller, spans, histogram rectangle, trapping rain water; and when a heap or monotonic deque fits better.
  • Python specifics: a list of indices with append/pop/[-1], [-1] * n for defaults, enumerate, and while stack and ... relying on short-circuit evaluation.

Code / implementation expected: Yes โ€” a short Python next-greater (or stock span) function using a list as the stack.

  • stack
  • monotonic

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonAll four variants on one array
PythonOnline stock span, counting pushes and pops

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 67 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you compute the diameter of a binary tree?

Continue