InterviewPrepKit

Home / Coding / Stack

Evaluate Reverse Polish Notation

medium Original β†—
Solving tips
  • Recognize RPN is built for a stack: push numbers, and on an operator pop the top two, apply, and push the result; one value remains as the answer.
  • Operand order matters: the first pop is the RIGHT operand and the second is the LEFT, which is what distinguishes 3 - 4 from 4 - 3.
  • Division truncates toward zero, so use int(a / b), never Python's floor-dividing // (13 // -5 is -3 but the answer should be -2).
  • Detect operators via set membership rather than str.isdigit(), which returns False for negatives like '-11'; target O(n) time and O(n) space.

Problem

You get an arithmetic expression as a list of tokens in Reverse Polish Notation (postfix): each token is either an integer (possibly negative) or one of the operators +, -, *, /. In RPN an operator comes after its two operands and applies to the two most recent unconsumed values β€” so there are no parentheses and no precedence rules.

Evaluate the expression and return the result as an integer. Division between integers truncates toward zero (so 6 / -132 is 0, and -7 / 2 is -3, not -4). The input is always a valid expression, and no division by zero occurs; every intermediate value fits in a 32-bit integer.

Examples

  • ["2", "1", "+", "3", "*"] β†’ 9 β€” means (2 + 1) * 3.
  • ["4", "13", "5", "/", "+"] β†’ 6 β€” means 4 + (13 / 5) and 13 / 5 truncates to 2.
  • ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] β†’ 22 β€” ((10 * (6 / ((9 + 3) * -11))) + 17) + 5; note 6 / -132 truncates toward zero to 0.

Constraints

  • 1 <= tokens.length <= 10^4
  • Each token is an operator or an integer in [-200, 200]

10^4 tokens sinks the rescan-and-splice simulation (O(n^2)); the expected solution is a single O(n) pass.

Think about it first

Hint 1 Evaluate `["2", "1", "+", "3", "*"]` by hand. When you reach `+`, which numbers does it consume? The two you saw *most recently* and haven't used yet.
Hint 2 "Most recently seen, not yet consumed" is a stack. What should happen to the stack when you read a number? When you read an operator?
Hint 3 Push numbers. On an operator, pop twice β€” the *first* pop is the right operand, the second is the left β€” apply, and push the result. One value remains at the end: the answer. Watch the division: Python's `//` floors, but the problem truncates toward zero.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.