Evaluate Reverse Polish Notation - Problem

You are given an array of strings tokens that represents an arithmetic expression in Reverse Polish Notation.

Evaluate the expression and return an integer that represents the value of the expression.

Note that:

  • The valid operators are '+', '-', '*', and '/'
  • Each operand may be an integer or another expression
  • The division between two integers always truncates toward zero
  • There will not be any division by zero
  • The input represents a valid arithmetic expression in reverse polish notation
  • The answer and all intermediate calculations can be represented in a 32-bit integer

Input & Output

Example 1 — Basic RPN Expression
$ Input: tokens = ["2","1","+","3","*"]
Output: 9
💡 Note: Step by step: Push 2, push 1, encounter '+' so pop 1 and 2, compute 2+1=3, push 3. Push 3, encounter '*' so pop 3 and 3, compute 3*3=9, push 9. Result is 9.
Example 2 — Division with Truncation
$ Input: tokens = ["4","13","5","/","+"]
Output: 6
💡 Note: Push 4, push 13, push 5, encounter '/' so pop 5 and 13, compute 13/5=2 (truncated), push 2. Encounter '+' so pop 2 and 4, compute 4+2=6.
Example 3 — Negative Result
$ Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
💡 Note: Complex expression that evaluates through multiple stack operations, handling negative numbers and multiple operators.

Constraints

  • 1 ≤ tokens.length ≤ 104
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200]

Visualization

Tap to expand
Reverse Polish Notation EvaluationInput Tokens21+3*Stack Processing33After "+":
3+1=3Final Result9Process: Push 2 → Push 1 → Pop 2, compute 2+1=3, push 3 → Push 3 → Pop 2, compute 3*3=9Expression evaluates to: 9
Understanding the Visualization
1
Input
Array of tokens representing RPN expression
2
Process
Use stack to evaluate: push numbers, pop and compute for operators
3
Output
Single integer result of the expression
Key Takeaway
🎯 Key Insight: RPN eliminates the need for parentheses by using postfix notation where operators follow their operands
Asked in
Amazon 25 Microsoft 18 Google 15 Facebook 12
185.0K Views
Medium Frequency
~15 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen