Home
DSA Patterns
Stack
Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation (LeetCode 150)
Evaluate Reverse Polish Notation (LeetCode 150): 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
5 TOKENS
READ TOKEN
tokens
i
stack
empty
a
:
b
:
Result
:
Read “2”
Next
A number: push 2
Tokens
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};
Evaluate Reverse Polish Notation in Python, Java, C++, TypeScript and C
Evaluate Reverse Polish Notation in Python
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for t in tokens:
if t in ("+", "-", "*", "/"):
b = stack.pop()
a = stack.pop()
if t == "+": stack.append(a + b)
elif t == "-": stack.append(a - b)
elif t == "*": stack.append(a * b)
else: stack.append(int(a / b))
else:
stack.append(int(t))
return stack[0]Evaluate Reverse Polish Notation in Java
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for (String t : tokens) {
if (t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/")) {
int b = stack.pop();
int a = stack.pop();
if (t.equals("+")) stack.push(a + b);
else if (t.equals("-")) stack.push(a - b);
else if (t.equals("*")) stack.push(a * b);
else stack.push(a / b);
} else {
stack.push(Integer.parseInt(t));
}
}
return stack.pop();
}
}Evaluate Reverse Polish Notation in C++
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (const string& t : tokens) {
if (t == "+" || t == "-" || t == "*" || t == "/") {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
if (t == "+") st.push(a + b);
else if (t == "-") st.push(a - b);
else if (t == "*") st.push(a * b);
else st.push(a / b);
} else {
st.push(stoi(t));
}
}
return st.top();
}
};Evaluate Reverse Polish Notation in TypeScript
function evalRPN(tokens: string[]): number {
const stack: number[] = [];
for (const t of tokens) {
if (t === '+' || t === '-' || t === '*' || t === '/') {
const b = stack.pop()!;
const a = stack.pop()!;
if (t === '+') stack.push(a + b);
else if (t === '-') stack.push(a - b);
else if (t === '*') stack.push(a * b);
else stack.push(Math.trunc(a / b));
} else {
stack.push(Number(t));
}
}
return stack[0];
};Evaluate Reverse Polish Notation in C
int evalRPN(char ** tokens, int tokensSize){
int* stack = (int*)malloc(tokensSize * sizeof(int));
int top = -1;
for (int i = 0; i < tokensSize; i++) {
char* t = tokens[i];
if (strlen(t) == 1 && (t[0] < '0' || t[0] > '9')) { // Operator
int b = stack[top--];
int a = stack[top--];
if (t[0] == '+') stack[++top] = a + b;
else if (t[0] == '-') stack[++top] = a - b;
else if (t[0] == '*') stack[++top] = a * b;
else stack[++top] = a / b;
} else {
stack[++top] = atoi(t);
}
}
int res = stack[top];
free(stack);
return res;
}More practice: DSA interview questions with answers · patterns cheat sheet
