Algo-Sim › Stacks & Monotonic Stack
Evaluate Reverse Polish Notation
Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input
Evaluate a postfix expression: push numbers, and let each operator combine the top two.
Problem
You are given tokens, an arithmetic expression in Reverse Polish Notation: each operator follows its two operands. Evaluate it and return the integer result. The operators are +, -, * and /, and division truncates toward zero.
Constraints
- 1 ≤ tokens.length ≤ 10⁴
- Each token is an operator or an integer in [-200, 200]
- The expression is valid and never divides by zero
- Every intermediate result fits in a 32-bit integer
Edge cases to test
- A single number
- Negative operands:
"-3"is a number, not an operator - Division truncates toward zero:
-7 / 2 = -3
Follow-up questions
- Why does Python need
int(a / b)? //floors toward −∞, while the task truncates toward 0;int(a / b)(ormath.trunc) matches Java and C++.- How would you turn infix into RPN?
- Shunting-yard: an operator stack ordered by precedence, flushed by lower-precedence operators and closing parentheses. O(n).
Solution
Java
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(), a = stack.pop();
stack.push(switch (t) {
case "+" -> a + b;
case "-" -> a - b;
case "*" -> a * b;
default -> a / b;
});
} else {
stack.push(Integer.parseInt(t));
}
}
return stack.pop();
}Python
def eval_rpn(tokens):
stack = []
for t in tokens:
if t in ('+', '-', '*', '/'):
b, a = stack.pop(), 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.pop()C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int evalRPN(vector<string> &tokens) {
deque<int> stack = {};
for (string t : tokens) {
if ((t == "+") || (t == "-") || (t == "*") || (t == "/")) {
int b = stack.back();
stack.pop_back();
int a = stack.back();
stack.pop_back();
int result = t == "+" ? a + b : t == "-" ? a - b
: t == "*" ? a * b
: a / b;
stack.push_back(result);
} else {
stack.push_back(stoi(t));
}
}
return stack.back();
}
};
More Stacks & Monotonic Stack problems
- Valid Parentheses (Easy)
- Implement Queue using Stacks (Easy)
- Basic Calculator II (Medium)
- Basic Calculator (Hard)
- Decode String (Medium)
- Asteroid Collision (Medium)
- Next Greater Element (Easy)
- Daily Temperatures (Medium)
- Remove K Digits (Medium)
- Online Stock Span (Medium)
- Car Fleet (Medium)
- Largest Rectangle in Histogram (Hard)
- Maximal Rectangle (Hard)
- Sliding Window Maximum (Hard)