← Back to DSA
#150
Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation solution for LeetCode 150, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Evaluate Reverse Polish Notation
Why it belongs on this sheet
This is simple stack mechanics, but it rewards calm implementation and correct operand ordering.
Pattern
Operand stack
Approach
Push numbers onto a stack. When an operator appears, pop the top two operands, apply the operator in the correct order, and push the result back.
Java solution
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for (String token : tokens) {
switch (token) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
int rightSub = stack.pop();
int leftSub = stack.pop();
stack.push(leftSub - rightSub);
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
int divisor = stack.pop();
int dividend = stack.pop();
stack.push(dividend / divisor);
break;
default:
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}
Complexity
- Time:
O(n) - Space:
O(n)
Interview note
Subtraction and division are where mistakes happen because order matters.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)