Home
DSA Patterns
Stack
Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation (Postfix).
Problem Understanding
The array tokens holds an arithmetic expression written in Reverse Polish Notation, where each operator comes after its two operands. Compute its value and return it as 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
Visualize how operands wait on the stack until an operator consumes them.
Dry Run
Input: ["4", "13", "5", "/", "+"]
| Token | Action | Stack |
|---|---|---|
4 |
Push 4 | [4] |
13 |
Push 13 | [4, 13] |
5 |
Push 5 | [4, 13, 5] |
/ |
Pop 5, 13. 13 / 5 = 2. Push 2. |
[4, 2] |
+ |
Pop 2, 4. 4 + 2 = 6. Push 6. |
[6] |
| End | Result | 6 |
Edge Cases & Common Mistakes
- Division Order:
a / bvsb / a. Remember: first popped isb(right operand). - Truncation: Integer division in Python behaves differently for negatives (
-1 // 2 = -1vs C++0). Useint(a / b)to truncate towards zero.
Solution
Stack Logic.
Evaluate Reverse Polish Notation Code
1var evalRPN = function(tokens) {2 const stack = [];3 for (const t of tokens) {4 if (t === '+' || t === '-' || t === '*' || t === '/') {5 const b = stack.pop();6 const a = stack.pop();7 if (t === '+') stack.push(a + b);8 else if (t === '-') stack.push(a - b);9 else if (t === '*') stack.push(a * b);10 else stack.push(Math.trunc(a / b));11 } else {12 stack.push(Number(t));13 }14 }15 return stack[0];16};
