Stack
Medium
Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation (Postfix).
10 min read
Problem Understanding
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression and return an integer.
Valid Operators: +, -, *, /. Integer division truncates toward zero.
Example:
- Input:
["2","1","+","3","*"] - Logic:
((2 + 1) * 3) = 9 - Output:
9 - Input:
["4","13","5","/","+"] - Logic:
(4 + (13 / 5)) = 6
Algorithm Strategy
RPN is perfectly suited for a Stack.
- Initialize an empty stack.
- Iterate through each token.
- If token is a number,
pushit to the stack. - If token is an operator:
popthe top two elements (saybis top,ais next).- Perform
a <op> b. pushthe result back.
- Final result is the only element left in the stack.
Interactive Visualization
Step 1 / 1
Empty Stack
Top Index: -1Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
