Skip to content
Decoder

Evaluate Reverse Polish Notation

Medium

Problem

In Reverse Polish Notation (RPN), an operator comes after its two operands: 3 4 + means 3 + 4, and 2 1 + 3 * means (2 + 1) * 3. Given a list of string tokens in RPN, return the value of the expression as an integer.

The operators are +, -, * and /. Division between two integers **truncates toward zero** (so 7 / -3 is -2, not -3).

Example 1

Input
["2", "1", "+", "3", "*"]
Output
9
Why
(2 + 1) * 3

Example 2

Input
["4", "13", "5", "/", "+"]
Output
6
Why
4 + 13 / 5

Example 3

Input
["7", "-3", "/"]
Output
-2

Constraints

  • 1 <= tokens.length <= 10^4
  • Each token is an operator or an integer in the range [-200, 200].
  • The expression is always valid and never divides by zero.
  • Every intermediate value fits in a 32-bit integer.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.