Skills101
← All coding problems

Evaluate Reverse Polish Notation

mediumStack & Queue+20 XPTime limit 2s

Evaluate an arithmetic expression written in Reverse Polish Notation (postfix), where every operator comes after its two operands: 2 1 + 3 * means (2 + 1) × 3 = 9.

Operators are +, -, * and /. Division between integers truncates toward zero (7 / -2 = -3, -7 / 2 = -3). Careful: Python's // rounds down instead!

Input:

  • line 1: n — the number of tokens
  • line 2: the n tokens separated by spaces

Output: the value of the expression.

Constraints: 1 ≤ n ≤ 10⁵. The expression is valid, there is never a division by zero, and every intermediate result fits in a 32-bit signed integer.

Think about it: a stack — push numbers; on an operator, pop two values (the second pop is the left operand), apply, push the result.

Sample input 1

5
2 1 + 3 *

Sample output 1

9

Sample input 2

5
4 13 5 / +

Sample output 2

6

Sample input 3

13
10 6 9 3 + -11 * / * 17 + 5 +

Sample output 3

22

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.