Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Evaluate a simple RPN expression

Compute the value of an expression given in Reverse Polish Notation using a stack.

Python practice7 minStacks & QueuesBeginnerLast updated March 27, 2026

Problem statement

Given an array of tokens representing an arithmetic expression in Reverse Polish Notation (RPN), evaluate the expression and return the result as an integer. The tokens may be integers (as strings) or the operators '+', '-', '*', '/'. For division, truncate toward zero (e.g., -7 / 3 -> -2). The input is guaranteed to be a valid RPN expression.

Task

Implement evaluate_rpn to evaluate tokenized RPN expressions with +, -, *, and / (integer division truncating toward zero).

Examples

Example 1

Input

evaluate_rpn(['2','1','+','3','*'])

Output

9

(2 + 1) * 3 = 9

Input format

A list of tokens (strings). Each token is either an integer literal or one of '+', '-', '*', '/'.

Output format

An integer representing the evaluated result.

Constraints

- 1 <= tokens.length <= 10^4 - Each token is either an integer represented as a string or one of '+', '-', '*', '/'. - Use integer arithmetic; division truncates toward zero.

Samples

Sample 1

Input

evaluate_rpn(['4','13','5','/','+'])

Output

6

13 / 5 = 2 (truncated), 4 + 2 = 6