Neural Mastery
← Practice
Evaluate Reverse Polish Notationmedium

Evaluate Reverse Polish Notation

medium Coding Interview Patterns 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Implement an RPN (postfix) calculator with a stack -- the representation that needs no parentheses and no operator precedence rules at all, because the OPERAND ORDER already encodes evaluation order.

Related Skills

Task

Implement eval_rpn(tokens): push every number onto a stack; on encountering an operator, pop the top two values (in the correct order: second-popped is the LEFT operand), apply the operator, and push the result back.

Function Signature

eval_rpn(tokens: list[str]) -> int

Examples

Example 1: Simple Expression
Input: tokens = ['2', '1', '+', '3', '*']
Output: 9
Explanation: (2 + 1) * 3 = 9
Example 2: Includes Division
Input: tokens = ['4', '13', '5', '/', '+']
Output: 6
Explanation: 4 + (13 / 5 truncated to 2) = 6

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Division truncates toward zero (use int(a / b), not the // floor-division operator, which rounds toward negative infinity for negative results).
  • The final answer is the single value left on the stack after processing every token.
Python3Saved ✓
def eval_rpn(tokens: list[str]) -> int:
"""tokens: a list of strings, each either an integer literal or one
of '+', '-', '*', '/'. Evaluate the Reverse Polish (postfix)
expression and return the integer result. Division between two
integers truncates toward zero (matches Python's int(a / b))."""
# Your implementation here
pass

Case 1: Simple Expression
Input: tokens = ['2', '1', '+', '3', '*']
Expected: 9
Case 2: Includes Division
Input: tokens = ['4', '13', '5', '/', '+']
Expected: 6