💡
Exercise 72

Evaluate Reverse Polish 20 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Reverse Polish Notation (RPN) puts operators after their operands. No parentheses needed!

# Normal: (2 + 1) * 3 # RPN: 2 1 + 3 * # Step-by-step: # Push 2 → [2] # Push 1 → [2, 1] # + → pop 1,2 → push 3 → [3] # Push 3 → [3, 3] # * → pop 3,3 → push 9 → [9] # Answer: 9

Algorithm using a stack:

  • If token is a number, push it onto the stack
  • If token is an operator (+, -, *, /), pop two values, compute, push result
  • The order matters for subtraction and division: second_popped OP first_popped
  • Division truncates toward zero: use int(a/b) not a//b

This is how calculators and compilers actually evaluate expressions!

📋 Instructions
Implement `eval_rpn(tokens)` to evaluate a Reverse Polish Notation expression. Test with ["2","1","+","3","*"] and ["4","13","5","/","+"].
For each token: if it's a digit (or negative number), push int(token). If it's an operator, pop b then a, compute a OP b, and push the result. Remember: int(a/b) truncates toward zero.
🧪 Test Cases
Input
eval_rpn(["2","1","+","3","*"])
Expected
9
Test case 1
Input
eval_rpn(["4","13","5","/","+"])
Expected
6
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.