Skip to content

Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation (RPN).

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

InputOutputExplanation
["2", "1", "+", "3", "*"]9(2 + 1) * 3 = 3 * 3 = 9
["4", "13", "5", "/", "+"]64 + (13 / 5) = 4 + 2 = 6
["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]22Complex nested operations = 22
["3", "4", "+"]73 + 4 = 7
["15"]15Single number is valid
  • 1 <= tokens.length <= 10^4
  • Each token is either an operator or a valid integer in range [-200, 200]
  • The input guarantees a valid RPN expression
ApproachTimeSpaceBest When
StackO(n)O(n)Straightforward iterative approach; most common
RecursiveO(n)O(n)You prefer recursion or need to understand the call stack visually

Both are optimal and equally valid.

Most Common
Stack-Based
O(n) time · O(n) space
Alternative
Recursive
O(n) time · O(n) space
Section titled “Approach 1: Stack-Based Evaluation (Recommended)”
★ Recommended

Iterate through tokens. Push operands onto the stack. When you see an operator, pop the required operands, compute, and push the result back.

The key insight: the stack automatically handles operator precedence because RPN is unambiguous — there are no parentheses to parse.

⏱ Time O(n) Single pass through tokens 💾 Space O(n) Stack size proportional to expression depth

Input: ["2", "1", "+", "3", "*"]

StepTokenStack (before)ActionStack (after)
1"2"[]Push 2[2]
2"1"[2]Push 1[2, 1]
3"+"[2, 1]Pop 1, 2 → 2+1=3[3]
4"3"[3]Push 3[3, 3]
5"*"[3, 3]Pop 3, 3 → 3*3=9[9]
Result9

Animated walkthrough

How the stack evaluates RPN expressions

Watch how operands are pushed and operators pop and compute. Notice the order of operations naturally flows from left to right.

Step 1 of 6 Target: RPN
Waiting to begin...
Array state
Memory / lookup state

function evaluateRpn(tokens):
stack = []
for token in tokens:
if token is an operator:
b = stack.pop()
a = stack.pop()
result = applyOperator(a, token, b)
stack.push(result)
else:
stack.push(int(token))
return stack[0]
evaluate_reverse_polish_notation_stack.py
from typing import List
def evaluate_rpn_stack(tokens: List[str]) -> int:
"""
Evaluate Reverse Polish Notation using a stack.
Time: O(n) - process each token once
Space: O(n) - stack stores operands
"""
stack = []
operators = {'+', '-', '*', '/'}
for token in tokens:
if token in operators:
# Pop two operands (order matters for - and /)
b = stack.pop()
a = stack.pop()
if token == '+':
result = a + b
elif token == '-':
result = a - b
elif token == '*':
result = a * b
else: # token == '/'
# Truncate towards zero (Python's int() does this)
result = int(a / b)
stack.append(result)
else:
# It's a number
stack.append(int(token))
return stack[0]
# Test cases
if __name__ == "__main__":
print(evaluate_rpn_stack(["2", "1", "+", "3", "*"])) # 9
print(evaluate_rpn_stack(["4", "13", "5", "/", "+"])) # 6
print(evaluate_rpn_stack(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])) # 22
print(evaluate_rpn_stack(["3", "4", "+"])) # 7
print(evaluate_rpn_stack(["3", "4", "*"])) # 12
🎯 Interview Favourite

Process tokens from right to left. When you encounter an operand, return it. When you encounter an operator, recursively get the two operands and apply the operator.

This mirrors the stack approach but uses the call stack instead of an explicit stack.

⏱ Time O(n) Single pass through tokens 💾 Space O(n) Recursion call stack depth

Input: ["4", "13", "5", "/", "+"]

Processing from right to left:

  1. See "+" → recursively get right operand
  2. See "/" → recursively get right operand (5), left operand (13) → 13 / 5 = 2
  3. Back to "+" → left operand is 4 → 4 + 2 = 6
function evaluateRpnRecursive(tokens, index):
token = tokens[index]
index--
if token is an operator:
right = evaluateRpnRecursive(tokens, index)
left = evaluateRpnRecursive(tokens, index)
return applyOperator(left, token, right)
else:
return int(token)
evaluate_reverse_polish_notation_recursive.py
from typing import List
def evaluate_rpn_recursive(tokens: List[str]) -> int:
"""
Evaluate Reverse Polish Notation using recursion with a shared index.
Time: O(n) - process each token once
Space: O(n) - recursion stack depth
"""
index = [len(tokens) - 1] # Use list to allow modification in nested function
operators = {'+', '-', '*', '/'}
def helper() -> int:
token = tokens[index[0]]
index[0] -= 1
if token in operators:
# Process in reverse order for recursion (right operand first)
b = helper()
a = helper()
if token == '+':
return a + b
elif token == '-':
return a - b
elif token == '*':
return a * b
else: # token == '/'
return int(a / b)
else:
return int(token)
return helper()
# Test cases
if __name__ == "__main__":
print(evaluate_rpn_recursive(["2", "1", "+", "3", "*"])) # 9
print(evaluate_rpn_recursive(["4", "13", "5", "/", "+"])) # 6
print(evaluate_rpn_recursive(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])) # 22
print(evaluate_rpn_recursive(["3", "4", "+"])) # 7
print(evaluate_rpn_recursive(["3", "4", "*"])) # 12
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
evaluate_reverse_polish_notation_space_optimized.py
"""
Solution for Evaluate Reverse Polish Notation
"""
def solve():
"""Implementation for approach 3 of Evaluate Reverse Polish Notation"""
pass
if __name__ == "__main__":
print("Solution ready")