Ctrl K

Postfix Calculator

Medium
An arithmetic expression is written in postfix form (reverse Polish notation): the operands come first and the operator follows them. For example, 3 4 + means 3 + 4, and 5 1 2 + * means 5 · (1 + 2). You are given a list of strings tokens, the items of such an expression in order. Each item is either an integer or one of the operators +, -, *, /. Evaluate the expression and return the result. Division is integer division that truncates toward zero (so 7 / -2 = -3). The expression is always well formed, there is never a division by zero, and the result as well as every intermediate value fits in a signed 32-bit integer.
Example 1
tokens=["7", "2", "-", "4", "*"] → 20

First 7 - 2 = 5, then 5 * 4 = 20.

Example 2
tokens=["9", "-4", "/", "3", "+"] → 1

9 / -4 = -2.25, truncated toward zero gives -2. Then -2 + 3 = 1.

Example 3
tokens=["42"] → 42
Constraints
  • 1 ≤ len(tokens) ≤ 10⁵
  • Each tokens[i] is an operator +, -, *, / or an integer from -200 to 200
  • Every intermediate value lies in [-2³¹, 2³¹ - 1]
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWhen Rail Robots Catch Up HardGrading the Arithmetic Quiz HardMerging Neighbors With a Common Factor HardTurn a Square Clockwise MediumRoll an Array to the Right Medium
loading Python…
Input
tokens=["7", "2", "-", "4", "*"]
Expected
20

Run checks the first 3 tests in your browser. Submit checks all 83 tests on the server, hidden ones included.