Evaluate Reverse Polish Notation LeetCode Solution

Difficulty Level Medium
Toptal VMvareViews 2988

Problem Statement

Evaluate Reverse Polish Notation LeetCode Solution – Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are `+``-``*`, and `/`. Each operand may be an integer or another expression.

Note that the division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate a result, and there will not be any division by zero operation.

```Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9```

Explanation

As we evaluate postfix expression manually we’ll follow the same approach of using a stack and performing an operation based on whether the current token is an operator or an operand.

Evaluating a postfix expression is even easier than evaluating a normal expression because you don’t have to worry about operator precedence.
The structure of postfix expression is as follows:
`ab*`, where a and b can be operands, or expressions themselves, and * is an operator.

So our task is to first evaluate a, then b, then combine them as (a * b).
This can be done easily using a stack.
We iterate over the whole string while maintaining a stack of operands, following this algorithm:

1. If the current token is an operation, go to step 2, else go to step 4
2. Pop the first two elements from the stack. They will be b and a respectively (as the order of the operands is reversed due to the stack).
3. Perform the requisite operation (a * b), and push the result back to the stack. go to step 5.
4. Push the integer representation of the current token to the stack.
5. Repeat steps 1 to 4 until the whole tokens array is traversed.
6. Return the top element of the stack.

Code

C++ Code for Evaluate Reverse Polish Notation

```class Solution {
public:
int evalRPN(vector<string>& tokens) {
unordered_map<string, function<int (int, int) > > map = {
{ "+" , [] (int a, int b) { return a + b; } },
{ "-" , [] (int a, int b) { return a - b; } },
{ "*" , [] (int a, int b) { return a * b; } },
{ "/" , [] (int a, int b) { return a / b; } }
};
std::stack<int> stack;
for (string& s : tokens) {
if (!map.count(s)) {
stack.push(stoi(s));
} else {
int op1 = stack.top();
stack.pop();
int op2 = stack.top();
stack.pop();
stack.push(map[s](op2, op1));
}
}
return stack.top();
}
};```

Java Code for Evaluate Reverse Polish Notation

```import java.util.Stack;

public class Solution {
public int evalRPN(String[] tokens) {
int a,b;
Stack<Integer> S = new Stack<Integer>();
for (String s : tokens) {
if(s.equals("+")) {
}
else if(s.equals("/")) {
b = S.pop();
a = S.pop();
}
else if(s.equals("*")) {
}
else if(s.equals("-")) {
b = S.pop();
a = S.pop();
}
else {
}
}
return S.pop();
}
}```

Python Code for Evaluate Reverse Polish Notation

```class Solution:
# @param {string[]} tokens
# @return {integer}
def __init__(self):
self.operators = {
'+': lambda y, x: x + y,
'-': lambda y, x: x - y,
'*': lambda y, x: x * y,
'/': lambda y, x: int(operator.truediv(x, y))
}

def evalRPN(self, tokens):
if not tokens:
return 0

stack = []

for token in tokens:
if token in self.operators:
stack.append(self.operators[token](stack.pop(), stack.pop()))
else:
stack.append(int(token))

return stack[0]```

O(N)

O(N)

Translate »
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://tutorialcup.com/leetcode-solutions/evaluate-reverse-polish-notation-leetcode-solution.htm", "fetch_time": 1726089069000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2024-38/segments/1725700651400.96/warc/CC-MAIN-20240911183926-20240911213926-00107.warc.gz", "warc_record_offset": 539307227, "warc_record_length": 19261, "token_count": 880, "char_count": 3396, "score": 4.0625, "int_score": 4, "crawl": "CC-MAIN-2024-38", "snapshot_type": "latest", "language": "en", "language_score": 0.8378803730010986, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00057-of-00064.parquet"}