/150. Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation

Medium
Arrays57.2% acceptance

Given a list of strings representing an arithmetic expression in Reverse Polish Notation (RPN), evaluate the expression and return its integer value. The valid operators are +, -, *, and /. Division between two integers truncates toward zero. The input is guaranteed to be a valid RPN expression, and there is no division by zero. All calculations and the result fit in a 32-bit signed integer.

Example 1

Input: [5,3,+,8,*]

Output: 64

Explanation: ((5 + 3) * 8) = 64

Example 2

Input: [7,2,/,4,-]

Output: -1

Explanation: ((7 / 2) - 4) = (3 - 4) = -1

Example 3

Input: [-3,-2,*,6,+]

Output: 12

Explanation: ((-3 * -2) + 6) = (6 + 6) = 12

Constraints

  • 1 <= len(rpn_tokens) <= 10_000
  • Each element in rpn_tokens is either +, -, *, /, or a string representing an integer in [-200, 200]
  • No division by zero occurs
  • All intermediate and final results fit in a 32-bit signed integer
Python (current runtime)

Case 1

Input: ['1','2','+','4','*']

Expected: 12

Case 2

Input: ['9','3','/','2','-']

Expected: 1

Case 3

Input: ['10','-5','+','2','*']

Expected: 10

Case 4

Input: ['100','200','+','50','/']

Expected: 6

Case 5

Input: ['-10','2','/','3','+']

Expected: -2