Practice Discrete Math

Algorithms / Stack Expression Evaluation

Least You Need to Know: Stacks, Postfix Evaluation, and Expression State

Stacks evaluate postfix expressions because operands arrive before the operator that combines them. When the operator appears, the most recent operands are popped, combined, and the result is pushed back for later use.

Least you need to know

  • Postfix notation places operators after their operands.
  • Operands are pushed as they appear.
  • When an operator appears, pop the required operands, apply the operator, and push the result.
  • Operand order matters for subtraction and division.
  • A valid postfix evaluation usually finishes with exactly one value on the stack.

Key notation

  • postfix — operator comes after its operands
  • push operand — store a numeric value for later combination
  • pop right then left — preserve operand order for noncommutative operators

Worked example

  • For 2 3 + 4 *, push 2, push 3, then + pops 3 and 2 and pushes 5.
  • Then push 4.
  • * pops 4 and 5 and pushes 20.
  • The final stack value is the expression result.

Common mistakes

  • Students sometimes pop operands in the wrong order for subtraction or division.
  • Each operator reduces the number of stack items by one in binary-operator expressions.
  • A correct final evaluation should leave one result, not many leftovers.

How to recognize it

  • The expression is postfix or reverse-polish notation.
  • The prompt says to evaluate while reading tokens left to right.
  • Operators combine the most recently available operands.

Next recommended lesson

Continue through this topic with Least You Need to Know: Bitmask Subset Enumeration and Used-Set State.

Least You Need to Know: Bitmask Subset Enumeration and Used-Set State

Related lessons

Keep going with nearby lessons in the same topic.

More ways to explore

Start practice