DSA AnimatorDSA animations
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.

How to solve Evaluate Reverse Polish Notation

LeetCode 150 · Medium · Stack · Pattern: Stack

Why the obvious approach is slow

Converting it back to normal notation with brackets is slow and complicated. The notation is designed to be evaluated with a stack.

The key idea

Read the tokens left to right. Push every number onto the stack. For an operator, pop two numbers, apply it, and push the result. Be careful with order: the first number popped is the right operand.

Remember

Operands go on the stack, operators pop two and push one. The first pop is the right operand.

Run the animation above on your own input, or watch the 1:11 video explanation of Evaluate Reverse Polish Notation with a dry run and Java code.

More Stack problems