← Back to Patterns
Data StructuresEasy

Stack

LIFO structure for tracking "not yet resolved" items waiting for their pair.

How it works

A Stack is a Last-In-First-Out (LIFO) data structure. In algorithm problems, it's used to track items that are "waiting for something" — an opening bracket waiting for its closing pair, an incomplete expression waiting for operands, or a bar in a histogram waiting for a taller bar on its right. The Monotonic Stack variant maintains the stack in increasing or decreasing order by popping elements that violate the order before pushing a new one. This efficiently answers "next greater element" queries in O(n). Stack is also the natural data structure for iterative DFS and for evaluating expressions with operator precedence.

Interactive Playground

empty

Stack is empty. LIFO — last in, first out.

Speed

When to use

  • Matching brackets or tags
  • Monotonic stack for next greater/smaller element
  • Expression evaluation and calculator problems

Tips

1For bracket matching: push opening brackets, and when a closing bracket appears, check if the top of the stack is the matching opener.
2Monotonic increasing stack (for next greater element): pop when current element > stack top, then current is the answer for all popped elements.
3Store indices in the stack instead of values when you need to calculate distances or spans.
4For calculator problems, handle operator precedence by processing operators in the right order when popping.

Common Mistakes

!Not checking if the stack is empty before popping — causes runtime errors.
!Confusing monotonic increasing vs decreasing stack direction.
!For bracket matching, not verifying the stack is empty at the end — leftover unmatched brackets should return false.
!Pushing closing brackets onto the stack — only opening brackets are pushed in the classic matching pattern.
💡 Key Insight:Push when unresolved, pop when the matching condition is met.