
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.
- Start with empty stack and process tokens left to right.
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.
- Start with empty stack and process tokens left to right.
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)
Editorial
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. |
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