Evaluate Reverse Polish Notation — Problem & Solution
Evaluate Reverse Polish Notation solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem.
Evaluate Reverse Polish Notation is a medium coding problem on arrays, math and stack.
- Difficulty: Medium
- Topics: Arrays, Math, Stack
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Evaluate an arithmetic expression given in Reverse Polish Notation (postfix). Valid operators are +, -, *, /. Division truncates toward zero. No division by zero occurs, and every expression is valid.
Example 1
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) × 3) = 9.
Example 2
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6.
Constraints
1 <= tokens.length <= 30Operands fit in 32-bit integers.
Hints for Evaluate Reverse Polish Notation
Hint 1
Push numbers; on an operator pop two, apply, push the result.
Hint 2
Order matters for - and /: the second pop is the left operand.
How to solve Evaluate Reverse Polish Notation
Postfix notation exists precisely so that no precedence rules and no parentheses are needed — the order of the tokens already encodes the tree. An operator always applies to the two subexpressions immediately before it, so operands can simply wait on a stack until an operator claims them.
Approach
- Scan the tokens left to right, keeping a stack of computed values.
- If the token is a number, push it.
- If it is an operator, pop twice. The first pop is the right operand
b, the second is the left operanda. - Compute
a op band push the result back — a finished subexpression is just another operand. - The single value left on the stack at the end is the answer.
Why it works
By induction, every value on the stack is a fully evaluated subexpression. When an operator is read, the expression is valid, so its two operands are the two most recently completed subexpressions — which are exactly the top two entries. Replacing them with the result keeps the invariant, so the last remaining value is the whole expression.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- Pop order is the classic bug.
ais the second pop. It makes no difference for+and*, but reversing it silently breaks-and/. - Division must truncate toward zero, not floor. In Python,
-7 // 2is-4— wrong here;int(-7 / 2)gives-3, which is why the solution divides then truncates. JavaScript needsMath.trunc, since/yields a float.
Reference solution
Python
from typing import List
def evalRPN(tokens: List[str]) -> int:
st = []
for t in tokens:
if t in ("+", "-", "*", "/"):
b = st.pop()
a = st.pop()
if t == "+":
st.append(a + b)
elif t == "-":
st.append(a - b)
elif t == "*":
st.append(a * b)
else:
st.append(int(a / b))
else:
st.append(int(t))
return st[0]Java
public static int evalRPN(String[] tokens) {
Deque<Integer> st = new ArrayDeque<>();
for (String t : tokens) {
if (t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/")) {
int b = st.pop();
int a = st.pop();
if (t.equals("+")) st.push(a + b);
else if (t.equals("-")) st.push(a - b);
else if (t.equals("*")) st.push(a * b);
else st.push(a / b);
} else {
st.push(Integer.parseInt(t));
}
}
return st.pop();
}C++
int evalRPN(vector<string>& tokens) {
vector<int> st;
for (const string& t : tokens) {
if (t == "+" || t == "-" || t == "*" || t == "/") {
int b = st.back(); st.pop_back();
int a = st.back(); st.pop_back();
if (t == "+") st.push_back(a + b);
else if (t == "-") st.push_back(a - b);
else if (t == "*") st.push_back(a * b);
else st.push_back(a / b);
} else {
st.push_back(stoi(t));
}
}
return st.back();
}JavaScript
var evalRPN = function(tokens) {
const st = [];
for (const t of tokens) {
if (t === "+" || t === "-" || t === "*" || t === "/") {
const b = st.pop(), a = 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(Math.trunc(a / b));
} else {
st.push(parseInt(t, 10));
}
}
return st[0];
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Stack Data Structure