All coding questions

Evaluate Reverse Polish Notation

medium
NeetCode 150stackmath

Problem

Given a list of tokens representing an arithmetic expression in postfix (Reverse Polish) notation, evaluate it. Operators are the four basic arithmetic operations and operands are integers.

Examples

Input: tokens = ["2", "1", "+", "3", "*"]
Output: 9
(2 + 1) * 3 = 9.
Input: tokens = ["4", "13", "5", "/", "+"]
Output: 6
4 + (13 / 5) = 6 with integer division.

Constraints

  • 1 <= tokens.length <= 10^4
  • Division truncates toward zero
  • Expression is always valid
Hints(tap to reveal)
  • 1. Push operands, pop two when you hit an operator.
  • 2. Order matters for subtraction and division.
Optimal approach(spoiler)
  1. Scan tokens left to right using a stack.
  2. Push numeric tokens onto the stack.
  3. On an operator, pop the two top operands, apply it in the correct order, and push the result.
  4. The final remaining value is the answer.
  5. O(n) time, O(n) space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor