← Back to DSA Animator
Evaluate Reverse Polish Notation LC #150 Medium Stack · Postfix
Problem

Evaluate an expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Division between two integers always truncates toward zero.

Example 1
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Constraints: 1 ≤ tokens.length ≤ 10⁴  |  tokens[i] is a valid integer or one of +, -, *, /
Try Examples
Custom:
Token Rail
Stack & Operation
Stack
empty
Waiting for operator…
ADD
Variables
token
a (top)
b (2nd)
op
result
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init empty stack, scan tokens left→right
2
Number token → stack.push(parseInt(t))
3
Operator → b = stack.pop(), a = stack.pop()
4
Compute a OP b, push result back onto stack
5
Return stack.pop() — the single remaining element
Time
O(n)
Space
O(n)
Why RPN + Stack?

RPN (postfix notation) is designed for stack evaluation. Operands wait on the stack until their operator arrives. When an operator appears, it always applies to the two most recent values — no parentheses or precedence rules needed. Stack size is at most O(n/2) for a balanced expression.