AAlgoLoopSpaced repetition for LeetCode
MEDIUMStack / QueueLeetCode ↗

Evaluate Reverse Polish Notation

The key idea

In postfix notation every operator acts on the two most recently produced values, so a stack is the perfect fit: push numbers, and on each operator pop the top two operands, apply it, and push the result back. The final stack holds exactly one value — the answer.

Problem

You are given an array of strings tokens that represents an arithmetic expression in Reverse Polish Notation (postfix notation).

Evaluate the expression and return an integer that represents its value.

Each tokens[i] is either an operator — "+", "-", "*", or "/" — or an integer. Note that:

- The valid operators are "+", "-", "*", and "/".
- Each operand may be an integer or another expression.
- The division between two integers always truncates toward zero.
- There will not be any division by zero.
- The input represents a valid arithmetic expression in Reverse Polish Notation.
- The answer and all intermediate calculations fit in a 32-bit integer.

Constraints

Examples

Input: tokens = ["2","1","+","3","*"] Output: 9
Input: tokens = ["4","13","5","/","+"] Output: 6
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] Output: 22

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Stack / Queue problems