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). Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero.

Example 1
  • Input: tokens = ["2", "1", "+", "3", "*"]
  • Output: 9
  • Explanation: Process "2", "1", "+" → 2 + 1 = 3, then "3", "3", "*" → 3 * 3 = 9
Example 2
  • Input: tokens = ["4", "13", "5", "/", "+"]
  • Output: 6
  • Explanation: Process "13", "5", "/" → 13 / 5 = 2 (truncated), then "4", "2", "+" → 4 + 2 = 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 can be represented in a 32-bit integer
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StackCognizanteBay
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 from the stack
  • Apply the operator to the two operands and push the result back onto the stack
  • 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
 Step 2: Iterate through each token in the RPN expression
 Step 3: If the token is a number, convert it to integer and push onto stack
 Step 4: If the token is an operator, pop two operands from the stack
 Step 5: Apply the operator to the two operands (first popped is second operand)
 Step 6: Push the result of the operation back onto the stack
 Step 7: Return the final result which is the only element left in the stack

Submitted Code :