Pattern

Stack

Track state with last-in-first-out order to match nested structure, parse expressions, or undo the most recent action first.

What it is

A stack holds elements so that only the most recently added one is ever accessed or removed next. That single property — last in, first out — is exactly what you need whenever a problem has a notion of "nesting" (brackets, recursive groups, function calls) or "the most recent thing takes priority" (undo history, the last operator in an expression). Most solutions in this hub are a single pass over the input with one stack, pushing when you open something or make progress, and popping when something closes or resolves.

When it applies

Tells in the problem

The classic mistake

Popping from the stack without first checking it's non-empty, or without checking that what's on top actually matches what's expected, is the error interviewers report most — this crashes or silently returns the wrong answer on inputs like a lone closing bracket or a stray unmatched operator that a hasty test case never exercised. It happens because the "happy path" of the pattern (open something, later close it) is where all the attention naturally goes, while the failure paths (something closes with nothing open, or the wrong kind of thing is open) get treated as edge cases to handle "later." Catch it by writing the empty-stack and mismatch checks in the same breath as the pop, not as an afterthought once the main logic works.

Questions to start with

All 10 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.