Tutorialspoint
Problem
Solution
Submissions

Reverse Polish Notation

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

Write a C# program to evaluate the value of an arithmetic expression in Reverse Polish Notation (RPN). RPN is a mathematical notation in which every operator follows all of its operands, for example: ["2", "1", "+", "3", "*"] represents (2 + 1) * 3 = 9. The valid operators are '+', '-', '*', and '/'. Each operand may be an integer or another expression. Division between two integers always truncates toward zero.

Example 1
  • Input: tokens = ["2", "1", "+", "3", "*"]
  • Output: 9
  • Explanation:
    • ((2 + 1) * 3) = 9
Example 2
  • Input: tokens = ["4", "13", "5", "/", "+"]
  • Output: 6
  • Explanation:
    • (4 + (13 / 5)) = 4 + 2 = 6
    • (Note that 13 / 5 = 2.6, but integer division truncates to 2.)
Constraints
  • 1 ≤ tokens.length ≤ 10^4
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200]
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StackD. E. ShawArctwist
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 to keep track of operands
  • When an operator is encountered, pop the required number of operands from the stack
  • Evaluate the expression with the operator and push the result back onto the stack
  • At the end, the stack will contain the final result
  • Be careful with division, as it truncates toward zero

Steps to solve by this approach:

 Step 1: Create a stack to store operands.

 Step 2: Iterate through each token in the input array.
 Step 3: If the token is a number, push it onto the stack.
 Step 4: If the token is an operator, pop the top two operands from the stack.
 Step 5: Evaluate the expression with the operator and the two operands.
 Step 6: Push the result of the evaluation back onto the stack.
 Step 7: After processing all tokens, the only item left on the stack is the final result.

Submitted Code :