Skip to content

Recognition guide

Stack clues: matching, next greater, and undo

Header art: nested arcs joining matching pairs of dots on the left, beside a tower of stacked slabs with an arrow into the top on the right.
A later item closes an earlier one, so the latest open item sits on top.

A stack gives you one thing: the most recent unfinished item is always on top. Problems that need a stack are problems where the newest open thing is the one you must deal with first. The code is short. The skill is hearing that sentence in the statement.

This guide is about that recognition. It does not re-teach the stack. For that, read the Stack pattern page. Here you learn the three families of clues, so you can decide before you write code.

The one-sentence test

Ask which earlier item the current item has to talk to.

  • If it must talk to the most recent one still open (a closer meets its opener, an undo meets the last action), you want a stack.
  • If it must talk to the oldest one waiting, you want a queue.
  • If it must talk to a whole slice, think sliding window or prefix sums instead.

Family 1: matching and nesting

  • "Valid parentheses", "balanced", "properly nested". Each closer must match the latest opener that has not been closed.
  • "Tags", "brackets", "blocks". Anything with an open and a close marker nests like this.
  • "Decode", "expand", "evaluate an expression". Inner pieces finish before outer ones, so the outer piece waits on the stack.

Family 2: the next greater (or smaller) value

  • "Next greater element", "next warmer day", "next taller". Each item waits until something bigger shows up.
  • "How many days until", "how far to the right". The answer for an item is the distance to the one that resolves it.
  • "Span", "largest rectangle in a histogram". Items that a newer one has beaten are dropped, and the rest are kept.

Here the stack holds items still waiting for an answer, usually as indexes. Each item is pushed once and popped once, so the whole scan is O(n).

Family 3: undo and most recent

  • "Undo", "backspace", "go back". The last action is the first to reverse.
  • "Simplify a path", "process commands". A "go up" removes the latest folder, so the latest folder must be easy to reach.
  • "Most recent", "latest", "last opened". When the statement says "most recent" and you only ever need the latest item, that is the top of the stack.

Counter-signals

These look like stack problems and are not.

  • "Process in the order they arrived." That is a queue. A stack serves the wrong end.
  • "Longest or shortest contiguous slice." That is a sliding window, even when the input is brackets or letters.
  • "Visit a graph by levels." Layer-by-layer is a queue. A stack gives you depth-first. See DFS vs BFS.
  • "Reverse the order." A single reversal is a loop or a built-in. You need a stack only when pieces finish at different times.
  • "Sorted row and a pair." Comparing both ends of a sorted row is two pointers, not a stack.

The decision checklist

  1. Does a later item close, cancel, or resolve an earlier one? Think stack.
  2. Is it always the latest unresolved item that gets resolved first? Stack. If it is the oldest, queue.
  3. Does each item wait for the next bigger or smaller one? Use a stack of waiting indexes.
  4. Is there an "undo" or "go back" step? Stack.
  5. Do you need only the final answer, not the order things are handled? A counter may be enough. A running balance is a stack that remembers only its size.

The next-greater scan

Each item waits on the stack until a bigger value arrives. Storing indexes gives you both the value and the distance.

TypeScript
function daysUntilWarmer(temps: number[]): number[] {
const answer = new Array<number>(temps.length).fill(0);
const waiting: number[] = []; // indexes whose warmer day has not come yet
for (let i = 0; i < temps.length; i++) {
while (waiting.length > 0 && temps[waiting[waiting.length - 1]] < temps[i]) {
const j = waiting.pop()!;
answer[j] = i - j; // day i is the first warmer day for j
}
waiting.push(i);
}
return answer; // anything left on the stack keeps 0
}
The idea applies in any language. A plain list or array works as the stack as long as you only use its end.

Three worked examples

  1. 1. "Given a string of brackets, decide whether it is valid."

    Clues: "valid" and "matching". Push each opener. On a closer, the top must be its partner, or the string is invalid. At the end the stack must be empty.

    Pattern: stack, matching.

  2. 2. "For each day's temperature, return how many days you wait for a warmer one."

    Clues: "next warmer" and "how many days". Each day waits until a hotter day arrives. Keep waiting indexes on the stack, and when a hotter day shows up, resolve every colder one on top.

    Pattern: stack, next greater.

  3. 3. "Type characters into an editor where `#` means backspace. Compare two typed strings."

    Clues: "backspace" and "most recent". Each # removes the last typed character. Process each string into a stack, then compare what is left.

    Pattern: stack, undo.

Common traps

  • Popping from an empty stack. A closer with nothing open is invalid, not a crash. Check before you pop.
  • Forgetting what is left at the end. An unmatched opener stays on the stack. The input is valid only if the stack ends empty.
  • Storing values when the answer needs distances. Store indexes. You can read the value from the index, but not the other way round.
  • Wrong comparison for equal values. "Next greater" means strictly greater. Decide whether an equal value resolves the item, and use < or <= on purpose.
  • Popping too much. In the next-greater scan, pop only while the top is resolved. Stop at the first item that is not.

Quick answers

What is the difference between a stack and recursion?

A recursive call uses the call stack for you. An explicit stack does the same job with your own list, which avoids a crash on very deep input.

When should I store indexes instead of values?

When the answer is a distance, a position, or a width. If you only need to compare values, values are enough.

Is a monotonic stack a different pattern?

It is the next-greater scan above: a stack kept in increasing or decreasing order by popping items that can no longer be the answer. It is still a stack.

Practice it on Algofily

Recognizing the pattern is a skill on its own, so Algofily trains it before you write code. Each problem moves through seven stages: Understand, Pattern, Think, Code, Tests, Debug, and Explain. In the Code stage, Algofily AI can give progressive hints (sign-in required).

  • Read the Stack pattern page for the matching-brackets walk-through, the next warmer minute, and the problems that practice it.
  • Wondering when to use a queue instead? See the Queue pattern page.

While you code, Algofily AI can ask a question and open the next hint.