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
Evaluate Reverse Polish Notation INPUT tokens array: "2" "1" "+" "3" "*" 0 1 2 3 4 Token Types: Numbers Operators Valid: + - * / Equivalent Infix: ((2 + 1) * 3) Use STACK to evaluate ALGORITHM STEPS 1 Push "2" Stack: [2] 2 Push "1" Stack: [2, 1] 3 Process "+" Pop 1,2 --> 2+1=3 Stack: [3] 4 Push "3" Stack: [3, 3] 5 Process "*" Pop 3,3 --> 3*3=9 Stack: [9] Stack Operations: 9 Final Number: PUSH Operator: POP 2 then PUSH result FINAL RESULT Output: 9 Calculation Trace: Step 1: Push 2 Step 2: Push 1 Step 3: 2 + 1 = 3 Step 4: Push 3 Step 5: 3 * 3 = 9 OK - Verified! (2+1)*3 = 9 Key Insight: RPN naturally uses a stack: numbers are pushed, operators pop two operands, compute, and push the result. Order matters for subtraction and division: second-popped is left operand, first-popped is right operand. Time Complexity: O(n) | Space Complexity: O(n) where n is the number of tokens. TutorialsPoint - Evaluate Reverse Polish Notation | Optimal Stack-Based Solution
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