Stack: how to spot it

Lesson 5.1 · Pattern lesson · 4 min · by Vinay C

We'll cover the following

Last in, first out. Park things you cannot finish yet, then resolve the most recent one as soon as the answer shows up.

How the question sounds

  • Next greater or smaller element, or how many days until warmer (monotonic stack)
  • Balanced brackets and other nested structures
  • Evaluate an expression, reverse Polish notation
  • Undo the last thing when the new thing cancels it
  • The most recent unfinished item must be handled first

The two shapes

Where it shows up in GenAI work

Parsing nested JSON from a model, checking balanced brackets in structured output or tool calls, and undo history in an editor are stack problems.

Is it stack?

Decide yes or no before you open each answer.

Check yourselfFor each day, how many days until a warmer temperature?

Yes. Next greater element, solved with a monotonic stack.

Check yourselfCheck that the brackets ()[]{} in a string are balanced.

Yes. The most recent opener must close first.

Check yourselfEvaluate an expression in reverse Polish notation.

Yes. Push operands, pop two when an operator arrives.

Check yourselfPrint a binary tree level by level.

No. Level by level is first in, first out, so a queue and BFS.

Check yourselfFind the maximum sum of 3 consecutive days.

No. A fixed sliding window.

Check yourselfFind the first unique character in a string.

No. Count with a hash map, then scan.

Problems in this pattern

  1. Valid parentheses · Easy · Matching
  2. Daily temperatures · Medium · Monotonic stack
  3. Evaluate reverse Polish notation · Medium · Operands
  4. Remove adjacent duplicates · Easy · Undo

Summary: say it in the interview

  • Matching: Push openers. A closer is only valid if it matches the item on top of the stack.
  • Monotonic: Keep the stack sorted. A new value pops everything it beats, and each popped item gets its answer.