Stacks

Use last-in-first-out stacks for matching brackets, evaluating expressions, undo history and simulating recursion.

Beginner · about 4 hours · difficulty 2/5

Learn first: Array and String Fundamentals

A stack supports push, pop and peek at one end in O(1). It is the right structure whenever the most recent unfinished item must be handled first.

Where stacks appear

  • Bracket matching: push opening brackets, pop and compare on closing ones.
  • Expression evaluation: evaluate postfix (Reverse Polish) directly; convert infix to postfix with operator precedence (shunting-yard), or evaluate a basic calculator with a stack of partial results and signs.
  • Nested decoding: Decode String ("3[a2[c]]") uses a stack of counts and partial strings.
  • Simulating recursion: an explicit stack turns recursive DFS into iterative DFS, which avoids stack overflow.
  • Min stack: store the current minimum alongside each element to get min in O(1).
  • Path simplification: Simplify Path pushes directory names and pops on "..".

Implementation

Use a dynamic array or std::stack, ArrayDeque in Java (not the legacy Stack class), or a Python list with append/pop. Implementing a stack with an array and with a linked list is a common viva and exam question.

Pitfalls

Popping from an empty stack, forgetting leftover elements at the end (unmatched brackets), and mixing up operand order for subtraction and division in RPN.

Key concepts

  • LIFO operations and implementations
  • Balanced brackets
  • Postfix evaluation and infix conversion
  • Min stack
  • Nested decoding
  • Iterative DFS with explicit stack

Mini project

Solve 7 problems: Valid Parentheses, Min Stack, Evaluate Reverse Polish Notation, Decode String, Simplify Path, Basic Calculator II, and Asteroid Collision.

Check yourself

How does Min Stack return the minimum in O(1) even after the current minimum is popped?

Free resources