InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Evaluate Reverse Polish Notation

medium Original ↗ 00:00

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]

With 10^4 tokens, a rescan-and-splice simulation is O(n^2) and too slow. 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug