15% off all plans & roadmaps Use code
See plansEvaluate Reverse Polish Notation
- LeetCode 150
- Medium
- Stack Patterns
- Expression Evaluation (RPN/Infix)
Updated
TL;DR: Evaluate a postfix expression given as string tokens. Push numbers on a stack, and when an operator appears, pop two values, apply it, and push the result back.
Problem
You are given an array of strings tokens that holds an arithmetic expression written in Reverse Polish Notation (postfix form). Evaluate the expression and return its value as an integer.
Keep these rules in mind:
- The valid operators are
+,-,*, and/. - Each operand is either an integer or the result of another sub-expression.
- Division between two integers always truncates toward zero.
- No expression divides by zero.
- The input is always a valid postfix expression.
- The final answer and every intermediate result fit in a 32-bit integer.
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
Example 3
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22
Constraints
1 <= tokens.length <= 10^4tokens[i]is either an operator ("+","-","*","/") or an integer in the range[-200, 200].
Constraints that matter
tokens.lengthup to 10^4 means an O(n^2) rescan is only tens of millions of steps, which is survivable but wasteful. A single O(n) pass is the target.- Tokens like
-11are numbers, not operators. You must test the whole token, not its first character. - Division truncates toward zero. Python's
//floors, so-6 // 132gives -1 and is wrong here. - The input is always valid and never divides by zero, so you do not need to guard against an empty stack or a zero divisor.
- Every intermediate value fits in 32 bits, so plain
intis safe in Java, C++ and C# and no big-number handling is needed.
Hints
Hint 1
This is the Stack pattern for expression evaluation.
Hint 2
Treat the token list as an expression you shrink in place.
Solution
Intuition
This is the Stack pattern for expression evaluation. In postfix notation the operator comes after its two operands, so you never need parentheses or precedence rules. The order of the tokens already encodes the order of the work.
Picture a stack of plates in a kitchen: each finished dish goes on top, and when a meal needs two things, you take the two plates on top. The stack is the set of unused values, and each operator consumes the top two and puts its result back.
Look at what an operator needs: the two most recent values that nobody has used yet. That is last-in, first-out behavior. A number you read cannot be used until you see its operator, so you park it. When an operator arrives, the top two parked values are exactly its operands.
The stack always holds finished sub-results that are waiting for a later operator. After you apply an operator, its result goes back on top, ready to be an operand for the next one. Because the input is valid, the stack ends with exactly one value, the answer.
One detail decides most wrong answers. The first value you pop is the right operand, and the second is the left. For + and * the order does not matter. For - and / it does.
Worked example
Input: tokens = ["4","13","5","/","+"] Output: 6 Explanation: The / token works on 13 and 5 and gives 2, because 13 / 5 = 2.6 truncates to 2. The + token then adds 4 and 2 to give 6. In infix form the expression is 4 + (13 / 5).
Approach 1: Brute force: rescan and collapse
Treat the token list as an expression you shrink in place. Find the first operator, take the two tokens before it, compute the result, and replace those three tokens with one token holding the result. Repeat until one token is left.
This works because the first operator in the list always has two plain numbers right before it. Everything to its left is a number, so nothing earlier can be reduced first.
Steps
- Copy
tokensinto a mutable list. - While the list has more than one token, scan from index 0 to find the first operator at index
i. - Parse the tokens at
i - 2andi - 1as integersaandb. - Compute
a op b, truncating division toward zero. - Replace the three tokens at
i - 2,i - 1,iwith the result as a string. - When one token remains, parse it and return it.
Dry run
Start with [4, 13, 5, /, +].
- Pass 1: the first operator is
/at index 3. The operands are 13 and 5. The result is 2. The list becomes[4, 2, +]. - Pass 2: the first operator is
+at index 2. The operands are 4 and 2. The result is 6. The list becomes[6]. - One token is left, so the answer is 6.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n) |
Let n be the number of tokens. A valid expression has about n / 2 operators, so the loop runs about n / 2 times. Each pass scans up to n tokens to find an operator and shifts up to n tokens when it deletes two of them, so a pass costs O(n). That gives O(n^2) in total, and the copied list uses O(n) space.
PythonTested in our runner
from typing import List
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
ops = {"+", "-", "*", "/"}
arr = list(tokens)
while len(arr) > 1:
i = 0
while arr[i] not in ops:
i += 1
a, b = int(arr[i - 2]), int(arr[i - 1])
if arr[i] == "+":
r = a + b
elif arr[i] == "-":
r = a - b
elif arr[i] == "*":
r = a * b
else:
r = int(a / b) # truncate toward zero
arr[i - 2:i + 1] = [str(r)]
return int(arr[0])
JavaTested in our runner
import java.util.*;
class Solution {
private boolean isOp(String s) {
return s.length() == 1 && "+-*/".indexOf(s.charAt(0)) >= 0;
}
public int evalRPN(String[] tokens) {
List<String> arr = new ArrayList<>(Arrays.asList(tokens));
while (arr.size() > 1) {
int i = 0;
while (!isOp(arr.get(i))) {
i++;
}
int a = Integer.parseInt(arr.get(i - 2));
int b = Integer.parseInt(arr.get(i - 1));
int r;
switch (arr.get(i).charAt(0)) {
case '+': r = a + b; break;
case '-': r = a - b; break;
case '*': r = a * b; break;
default: r = a / b;
}
arr.set(i - 2, String.valueOf(r));
arr.remove(i);
arr.remove(i - 1);
}
return Integer.parseInt(arr.get(0));
}
}
C++Tested in our runner
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
vector<string> arr = tokens;
while (arr.size() > 1) {
int i = 0;
while (!(arr[i].size() == 1 && string("+-*/").find(arr[i][0]) != string::npos)) {
i++;
}
int a = stoi(arr[i - 2]);
int b = stoi(arr[i - 1]);
int r;
switch (arr[i][0]) {
case '+': r = a + b; break;
case '-': r = a - b; break;
case '*': r = a * b; break;
default: r = a / b;
}
arr[i - 2] = to_string(r);
arr.erase(arr.begin() + i - 1, arr.begin() + i + 1);
}
return stoi(arr[0]);
}
};
JavaScriptTested in our runner
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function(tokens) {
const isOp = (t) => t === "+" || t === "-" || t === "*" || t === "/";
const arr = tokens.slice();
while (arr.length > 1) {
let i = 0;
while (!isOp(arr[i])) {
i++;
}
const a = Number(arr[i - 2]);
const b = Number(arr[i - 1]);
let r;
if (arr[i] === "+") r = a + b;
else if (arr[i] === "-") r = a - b;
else if (arr[i] === "*") r = a * b;
else r = (a / b) | 0; // truncate toward zero
arr.splice(i - 2, 3, String(r));
}
return Number(arr[0]);
};
GoTested in our runner
import "strconv"
func isOpBrute(s string) bool {
return s == "+" || s == "-" || s == "*" || s == "/"
}
func evalRPN(tokens []string) int {
arr := append([]string{}, tokens...)
for len(arr) > 1 {
i := 0
for !isOpBrute(arr[i]) {
i++
}
a, _ := strconv.Atoi(arr[i-2])
b, _ := strconv.Atoi(arr[i-1])
var r int
switch arr[i] {
case "+":
r = a + b
case "-":
r = a - b
case "*":
r = a * b
default:
r = a / b
}
arr[i-2] = strconv.Itoa(r)
arr = append(arr[:i-1], arr[i+1:]...)
}
res, _ := strconv.Atoi(arr[0])
return res
}
C#Tested in our runner
public class Solution {
private bool IsOp(string s) {
return s == "+" || s == "-" || s == "*" || s == "/";
}
public int evalRPN(string[] tokens) {
List<string> arr = new List<string>(tokens);
while (arr.Count > 1) {
int i = 0;
while (!IsOp(arr[i])) {
i++;
}
int a = int.Parse(arr[i - 2]);
int b = int.Parse(arr[i - 1]);
int r;
if (arr[i] == "+") r = a + b;
else if (arr[i] == "-") r = a - b;
else if (arr[i] == "*") r = a * b;
else r = a / b;
arr[i - 2] = r.ToString();
arr.RemoveRange(i - 1, 2);
}
return int.Parse(arr[0]);
}
}
Approach 2: Single pass with prev links
What's slow: every pass rescans from index 0 and shifts the array after each deletion. The scan is repeated work, because operators are already in the order you need to process them. The shifting is repeated work too, because you only need to know which earlier slot holds each operand.
The insight that fixes it: walk the tokens once, left to right, and give each slot a prev link to the nearest unused value on its left. When you reach an operator, its operands sit at prev[i] and prev[prev[i]]. Compute the result into the operator's own slot, then point prev[i] past both operands. Nothing is ever moved, so deletion costs O(1).
Steps
- Create
valsof length n andprevwhereprev[i] = i - 1. - For each index
i, if the token is a number, store its integer invals[i]. - If it is an operator, set
right = prev[i]andleft = prev[right]. - Compute
vals[left] op vals[right]and store it invals[i]. - Set
prev[i] = prev[left]so the two operands are skipped from now on. - After the loop, return
vals[n - 1], because the last token is the root of the expression.
Dry run
Tokens are [4, 13, 5, /, +] at indices 0 to 4. Start with prev = [-1, 0, 1, 2, 3] and vals = [4, 13, 5, ?, ?].
- i = 3 (
/):right = prev[3] = 2,left = prev[2] = 1.vals[3] = 13 / 5 = 2. Setprev[3] = prev[1] = 0. - i = 4 (
+):right = prev[4] = 3,left = prev[3] = 0.vals[4] = 4 + 2 = 6. Setprev[4] = prev[0] = -1. - Return
vals[4] = 6.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of tokens. The loop visits each index once and does a fixed number of array reads, one arithmetic operation and one link update per index, so time is O(n). The vals and prev arrays each hold n entries, so space is O(n). This is the stack idea in disguise: the chain of prev links is the stack.
PythonTested in our runner
from typing import List
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
n = len(tokens)
vals = [0] * n
prev = list(range(-1, n - 1))
for i, t in enumerate(tokens):
if t in ("+", "-", "*", "/"):
right = prev[i]
left = prev[right]
a, b = vals[left], vals[right]
if t == "+":
vals[i] = a + b
elif t == "-":
vals[i] = a - b
elif t == "*":
vals[i] = a * b
else:
vals[i] = int(a / b)
prev[i] = prev[left] # skip both operands
else:
vals[i] = int(t)
return vals[n - 1]
JavaTested in our runner
import java.util.*;
class Solution {
public int evalRPN(String[] tokens) {
int n = tokens.length;
int[] vals = new int[n];
int[] prev = new int[n];
for (int i = 0; i < n; i++) {
prev[i] = i - 1;
}
for (int i = 0; i < n; i++) {
String t = tokens[i];
if (t.length() == 1 && "+-*/".indexOf(t.charAt(0)) >= 0) {
int right = prev[i];
int left = prev[right];
int a = vals[left];
int b = vals[right];
switch (t.charAt(0)) {
case '+': vals[i] = a + b; break;
case '-': vals[i] = a - b; break;
case '*': vals[i] = a * b; break;
default: vals[i] = a / b;
}
prev[i] = prev[left];
} else {
vals[i] = Integer.parseInt(t);
}
}
return vals[n - 1];
}
}
C++Tested in our runner
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int n = tokens.size();
vector<int> vals(n, 0);
vector<int> prev(n);
for (int i = 0; i < n; i++) {
prev[i] = i - 1;
}
for (int i = 0; i < n; i++) {
const string& t = tokens[i];
if (t.size() == 1 && string("+-*/").find(t[0]) != string::npos) {
int right = prev[i];
int left = prev[right];
int a = vals[left];
int b = vals[right];
switch (t[0]) {
case '+': vals[i] = a + b; break;
case '-': vals[i] = a - b; break;
case '*': vals[i] = a * b; break;
default: vals[i] = a / b;
}
prev[i] = prev[left];
} else {
vals[i] = stoi(t);
}
}
return vals[n - 1];
}
};
JavaScriptTested in our runner
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function(tokens) {
const n = tokens.length;
const vals = new Array(n).fill(0);
const prev = new Array(n);
for (let i = 0; i < n; i++) {
prev[i] = i - 1;
}
for (let i = 0; i < n; i++) {
const t = tokens[i];
if (t === "+" || t === "-" || t === "*" || t === "/") {
const right = prev[i];
const left = prev[right];
const a = vals[left];
const b = vals[right];
if (t === "+") vals[i] = a + b;
else if (t === "-") vals[i] = a - b;
else if (t === "*") vals[i] = a * b;
else vals[i] = (a / b) | 0;
prev[i] = prev[left];
} else {
vals[i] = Number(t);
}
}
return vals[n - 1];
};
GoTested in our runner
import "strconv"
func evalRPN(tokens []string) int {
n := len(tokens)
vals := make([]int, n)
prev := make([]int, n)
for i := 0; i < n; i++ {
prev[i] = i - 1
}
for i, t := range tokens {
if t == "+" || t == "-" || t == "*" || t == "/" {
right := prev[i]
left := prev[right]
a, b := vals[left], vals[right]
switch t {
case "+":
vals[i] = a + b
case "-":
vals[i] = a - b
case "*":
vals[i] = a * b
default:
vals[i] = a / b
}
prev[i] = prev[left]
} else {
v, _ := strconv.Atoi(t)
vals[i] = v
}
}
return vals[n-1]
}
C#Tested in our runner
public class Solution {
public int evalRPN(string[] tokens) {
int n = tokens.Length;
int[] vals = new int[n];
int[] prev = new int[n];
for (int i = 0; i < n; i++) {
prev[i] = i - 1;
}
for (int i = 0; i < n; i++) {
string t = tokens[i];
if (t == "+" || t == "-" || t == "*" || t == "/") {
int right = prev[i];
int left = prev[right];
int a = vals[left];
int b = vals[right];
if (t == "+") vals[i] = a + b;
else if (t == "-") vals[i] = a - b;
else if (t == "*") vals[i] = a * b;
else vals[i] = a / b;
prev[i] = prev[left];
} else {
vals[i] = int.Parse(t);
}
}
return vals[n - 1];
}
}

Solution pattern
Expression Evaluation (RPN/Infix)
Part of Stack Patterns
Approach 3: One-pass stackOptimalExpression Evaluation (RPN/Infix)
What's slow: nothing in time, since the previous approach is already O(n). What is clumsy is the bookkeeping. Two parallel arrays and index links describe a structure that a stack gives you directly.
The insight that fixes it: push each number onto a stack, and let each operator pop its two operands and push the result. The top of the stack is always the nearest unused value, which is what prev was tracking. You store only live values, so the stack holds at most the numbers still waiting for an operator.
Why it is correct. The stack always holds exactly the values that have been computed but not yet consumed, in the order they appear. Because each operator in postfix applies to the two most recent unused values, popping the top two gives its true operands. Valid input leaves a single value on the stack, which is the full expression result.
Steps
- Create an empty stack of integers.
- For each token, check whether it is exactly
+,-,*or/. - If it is a number, parse it and push it.
- If it is an operator, pop
bfirst (right operand), then popa(left operand). - Compute
a op b, with division truncating toward zero, and push the result. - After the last token, the stack holds one value. Return it.
Dry run
Tokens are [4, 13, 5, /, +].
| Token | Action | Stack after |
|---|---|---|
| 4 | push 4 | [4] |
| 13 | push 13 | [4, 13] |
| 5 | push 5 | [4, 13, 5] |
| / | pop b = 5, pop a = 13, push 13 / 5 = 2 | [4, 2] |
| + | pop b = 2, pop a = 4, push 4 + 2 = 6 | [6] |
The stack holds one value, 6, so the answer is 6.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of tokens. Each token is processed once, and each push, pop and arithmetic step costs O(1), so time is O(n). Every number is pushed once and every operator removes one value net, so the stack never exceeds the count of numbers. In the worst case, such as 1 2 3 4 + + +, all numbers sit on the stack before any operator runs, so space is O(n).
PythonTested in our runner
from typing import List
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack: List[int] = []
for token in tokens:
if token in ("+", "-", "*", "/"):
b = stack.pop() # right operand comes off first
a = stack.pop()
if token == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*":
stack.append(a * b)
else:
# // floors, so truncate with float division instead
stack.append(int(a / b))
else:
stack.append(int(token))
return stack[0]
JavaTested in our runner
import java.util.*;
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for (String t : tokens) {
if (t.length() == 1 && "+-*/".indexOf(t.charAt(0)) >= 0) {
int b = stack.pop();
int a = stack.pop();
int r;
switch (t.charAt(0)) {
case '+': r = a + b; break;
case '-': r = a - b; break;
case '*': r = a * b; break;
default: r = a / b; // truncates toward zero
}
stack.push(r);
} else {
stack.push(Integer.parseInt(t));
}
}
return stack.pop();
}
}
C++Tested in our runner
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
vector<int> st;
for (const string& t : tokens) {
if (t.size() == 1 && string("+-*/").find(t[0]) != string::npos) {
int b = st.back();
st.pop_back();
int a = st.back();
st.pop_back();
int r;
switch (t[0]) {
case '+': r = a + b; break;
case '-': r = a - b; break;
case '*': r = a * b; break;
default: r = a / b; // truncates toward zero
}
st.push_back(r);
} else {
st.push_back(stoi(t));
}
}
return st.back();
}
};
JavaScriptTested in our runner
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function(tokens) {
const stack = [];
for (const t of tokens) {
if (t === "+" || t === "-" || t === "*" || t === "/") {
const b = stack.pop();
const a = stack.pop();
let r;
if (t === "+") r = a + b;
else if (t === "-") r = a - b;
else if (t === "*") r = a * b;
else r = (a / b) | 0; // truncate toward zero, avoids -0
stack.push(r);
} else {
stack.push(Number(t));
}
}
return stack[0];
};
GoTested in our runner
import "strconv"
func evalRPN(tokens []string) int {
stack := make([]int, 0, len(tokens))
for _, t := range tokens {
switch t {
case "+", "-", "*", "/":
b := stack[len(stack)-1]
a := stack[len(stack)-2]
stack = stack[:len(stack)-2]
var r int
switch t {
case "+":
r = a + b
case "-":
r = a - b
case "*":
r = a * b
default:
r = a / b // Go truncates toward zero
}
stack = append(stack, r)
default:
v, _ := strconv.Atoi(t)
stack = append(stack, v)
}
}
return stack[0]
}
C#Tested in our runner
public class Solution {
public int evalRPN(string[] tokens) {
Stack<int> stack = new Stack<int>();
foreach (string t in tokens) {
if (t == "+" || t == "-" || t == "*" || t == "/") {
int b = stack.Pop();
int a = stack.Pop();
int r;
if (t == "+") r = a + b;
else if (t == "-") r = a - b;
else if (t == "*") r = a * b;
else r = a / b; // truncates toward zero
stack.Push(r);
} else {
stack.Push(int.Parse(t));
}
}
return stack.Pop();
}
}
Common mistakes
- Computing
b - aorb / abecause the first pop is the right operand. Name the popsb = pop()thena = pop()and computea op b. - Using
a // bin Python. It floors, so-6 // 132is -1 where the answer is 0. Useint(a / b), which truncates toward zero. - Detecting a subtraction by
token[0] == '-'. The token-11starts with a minus sign and is a number. Compare the whole token against the four operator strings. - Parsing every token with
int(token)before checking for an operator.int("+")raises an error. Test for an operator first and parse only in the number branch. - Returning
stack[-1]without trusting the input, or adding extra empty-stack checks that change behavior. The input is valid, so exactly one value remains andstack[0]is the answer. - Deleting from the middle of a list to mimic collapsing the expression. Each deletion shifts the tail and the total becomes O(n^2). Keep the stack at its top end.
Edge cases
["5"]: a single number with no operator returns 5.["3","-4","*"]: a negative operand gives -12. The token-4must parse as a number.["7","-2","/"]: 7 / -2 is -3.5 and truncates to -3, not -4.["1","2","-"]: operand order matters, so the result is -1, not 1.["-1","5","/"]: -1 / 5 truncates to 0. In JavaScript, use| 0so the result is 0 and not -0.- A long chain such as 5000 numbers followed by 4999
+tokens: the stack grows to 5000 entries and the sum stays within 32 bits.
Follow-ups interviewers ask
- Can you evaluate it recursively instead of with a stack?
- Yes. Start at the last token, which is the root operator. Recursively evaluate the right operand first, then the left, and combine them. It is O(n) time, but recursion depth can reach n, around 5000 for the largest inputs, so Python needs an iterative version or a raised limit.
- How would you handle an infix expression like 2 + 3 * 4 instead?
- Convert it to postfix with the shunting-yard algorithm, which uses an operator stack and precedence rules, then run the stack evaluator above. You can also evaluate directly with one stack for numbers and one for operators. Parentheses push and pop that operator stack.
- How would you detect an invalid expression?
- Check the stack size. An operator that finds fewer than two values means too many operators. A final stack size other than one means too many operands. Also reject unknown tokens and watch for division by zero before dividing.
Evaluate Reverse Polish Notation FAQ
What is the time complexity of Evaluate Reverse Polish Notation?
The stack solution is O(n) time and O(n) space, where n is the number of tokens. Each token is read once and costs a constant number of push, pop and arithmetic steps. The brute force rescan version is O(n^2).
Why use a stack for Evaluate Reverse Polish Notation?
An operator always applies to the two most recent unused values, which is last-in, first-out access. A stack gives you those values in O(1) and stores each result for the next operator. No precedence logic is needed.
How do you handle division in Evaluate Reverse Polish Notation in Python?
Use int(a / b) instead of a // b. Floor division rounds toward negative infinity, so negative quotients come out one too small. Java, C++, Go and C# already truncate toward zero with /. In JavaScript use Math.trunc or | 0.
Can Evaluate Reverse Polish Notation be solved in O(1) extra space?
Not in general. An expression like 1 2 3 4 + + + needs all four numbers held until the first operator appears, so the live values grow with n. You can reuse the input array as the stack to avoid a second structure, but that is still O(n) storage, kept in place.
Which operand is the left one when an operator pops two values?
The second value popped is the left operand and the first value popped is the right operand. For ["4","13","5","/"] the pops return 5 then 13, so the computation is 13 / 5. Reversing them gives 5 / 13 = 0.
Why is a token like -11 not treated as an operator in LeetCode 150?
Operators are single-character tokens equal to +, -, * or /. The token -11 has length 3 and parses as an integer. Compare the full token against the operator set instead of looking at its first character.
Asked at
See which companies ask this — Pro
Related problems
- Basic Calculator II · same technique: Expression Evaluation (RPN/Infix)
- Basic Calculator · same technique: Expression Evaluation (RPN/Infix)
- Basic Calculator III · same technique: Expression Evaluation (RPN/Infix)
- Min Stack · same pattern: Stack Patterns
- Daily Temperatures · same pattern: Stack Patterns
- Car Fleet · same pattern: Stack Patterns
- Valid Parenthesis String · same pattern: Stack Patterns
- Simplify Path · same pattern: Stack Patterns
- Decode String · same pattern: Stack Patterns
- Asteroid Collision · same pattern: Stack Patterns