Tutorialspoint
Problem
Solution
Submissions

Reverse Polish Notation

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to evaluate the value of an arithmetic expression in Reverse Polish Notation (RPN). Valid operators are +, -, *, and /. Each operand may be an integer or another expression. The division between two integers should truncate toward zero.

Example 1
  • Input: tokens = ["2","1","+","3","*"]
  • Output: 9
  • Explanation:
    • Start with empty stack and process tokens left to right.
    • Push "2" and "1" onto stack. Stack: [2, 1].
    • Encounter "+", pop 1 and 2, compute 2+1=3, push 3.
    • Stack: [3]. Push "3" onto stack. Stack: [3, 3].
    • Encounter "*", pop 3 and 3, compute 3*3=9, push 9.
    • Stack: [9]. Return final result: 9.
Example 2
  • Input: tokens = ["4","13","5","/","+"]
  • Output: 6
  • Explanation:
    • Start with empty stack and process tokens left to right.
    • Push "4", "13", "5" onto stack. Stack: [4, 13, 5].
    • Encounter "/", pop 5 and 13, compute 13/5=2 (truncated), push 2.
    • Stack: [4, 2]. Encounter "+", pop 2 and 4, compute 4+2=6, push 6.
    • Stack: [6]. Return final result: 6.
Constraints
  • 1 ≤ tokens.length ≤ 10^4
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200]
  • The given RPN expression is always valid
  • The answer and all the intermediate calculations fit in a 32-bit integer
  • Division between two integers should truncate toward zero
  • Time Complexity: O(n)
  • Space Complexity: O(n)
Functions / MethodsStackCapgeminiEY
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a stack data structure to store operands
  • Iterate through each token in the expression
  • If the token is a number, push it onto the stack
  • If the token is an operator, pop two operands and perform the operation
  • Push the result back onto the stack and continue
  • The final result will be the only element left in the stack

Steps to solve by this approach:

 Step 1: Initialize an empty stack to store operands during evaluation.

 Step 2: Create a set of valid operators for quick lookup.
 Step 3: Iterate through each token in the input array.
 Step 4: If token is a number, convert to integer and push onto stack.
 Step 5: If token is an operator, pop two operands from stack (maintain order for subtraction/division).
 Step 6: Perform the operation and push the result back onto the stack.
 Step 7: Return the final result which will be the only element remaining in the stack.

Submitted Code :