Skip to content

Commit f75ae32

Browse files
committed
✨ (solution): Problem 150. Evaluate Reverse Polish Notation
Add solution of 150. Evaluate Reverse Polish Notation
1 parent 162e114 commit f75ae32

File tree

3 files changed

+163
-0
lines changed

3 files changed

+163
-0
lines changed
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
---
2+
comments: true
3+
difficulty: medium
4+
# Follow `Topics` tags
5+
tags:
6+
- Array
7+
- Math
8+
- Stack
9+
---
10+
11+
# [150. Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/description/)
12+
13+
## Description
14+
15+
An array of strings called `tokens`, which represents an arithmetic expression written in Reverse Polish Notation (RPN).
16+
17+
Your task is to evaluate this expression and return the result as an integer.
18+
19+
Keep in mind:
20+
21+
- Valid operators include `+`, `-`, `*`, and `/`.
22+
- Each operand is either an integer or another valid RPN sub-expression.
23+
- Division between two integers should truncate toward zero.
24+
- You won't need to handle any division by zero.
25+
- The input is guaranteed to form a valid RPN expression.
26+
- Both the final result and all intermediate computations will fit within a 32-bit signed integer.
27+
28+
29+
**Example 1:**
30+
```
31+
Input: tokens = ['3', '2', '+', '2', '*']
32+
Output: 10
33+
Explanation: (3 + 2) * 2 = 10
34+
```
35+
36+
**Example 2:**
37+
```
38+
Input: tokens = ['3', '14', '5', '/', '+']
39+
Output: 5
40+
Explanation: (14 / 5) + 3 = 5
41+
```
42+
43+
**Constraints:**
44+
45+
* `1 <= tokens.length <= 10^4`
46+
* `tokens[i]` is either an operator: `"+"`, `"-"`, `"*"`, or `"/"`, or an integer in the range `[-200, 200]`.
47+
48+
49+
## Solution
50+
51+
This is a classic postfix expression problem. We use a stack to store operands when encountering numbers, and apply operators by popping values from the stack when an operator is found.
52+
53+
```java
54+
class Solution {
55+
public int evalRPN(String[] tokens) {
56+
57+
Stack<Integer> stack = new Stack<>();
58+
for (String token : tokens) {
59+
if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
60+
int first = stack.pop();
61+
int second = stack.pop();
62+
/* In Java, when using switch with String, the compiler generates code that compares hashCode() first, then uses .equals() for exact match. This makes the average time complexity close to O(1), but the worst-case complexity is O(k), where k is the string length. Therefore, for performance-critical code, using a Map lookup or interning strings for reference comparison can be faster than a switch or chained if-else. */
63+
if (token.equals("+")) {
64+
stack.push(second + first);
65+
} else if (token.equals("-")) {
66+
stack.push(second - first);
67+
} else if (token.equals("*")) {
68+
stack.push(second * first);
69+
} else if (token.equals("/")) {
70+
stack.push(second / first);
71+
}
72+
73+
} else {
74+
stack.push(Integer.parseInt(token));
75+
}
76+
}
77+
return stack.peek();
78+
}
79+
}
80+
```
81+
82+
```python
83+
class Solution:
84+
def evalRPN(self, tokens: list[str]) -> int:
85+
86+
ops = {
87+
'+': operator.add,
88+
'-': operator.sub,
89+
'*': operator.mul,
90+
'/': operator.truediv,
91+
}
92+
93+
stack = []
94+
for token in tokens:
95+
if token in "+-*/":
96+
first, second = stack.pop(), stack.pop()
97+
if token != "/":
98+
stack.append(ops[token](second, first))
99+
else:
100+
stack.append(int(second / first))
101+
else:
102+
stack.append(int(token))
103+
return stack[0]
104+
```
105+
106+
## Complexity
107+
108+
- Time complexity: $$O(n)$$
109+
<!-- Add time complexity here, e.g. $$O(n)$$ -->
110+
111+
- Space complexity: $$O(n)$$
112+
<!-- Add space complexity here, e.g. $$O(n)$$ -->
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
public int evalRPN(String[] tokens) {
5+
6+
Stack<Integer> stack = new Stack<>();
7+
for (String token : tokens) {
8+
if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
9+
int first = stack.pop();
10+
int second = stack.pop();
11+
/* In Java, when using switch with String, the compiler generates code that compares hashCode() first, then uses .equals() for exact match. This makes the average time complexity close to O(1), but the worst-case complexity is O(k), where k is the string length. Therefore, for performance-critical code, using a Map lookup or interning strings for reference comparison can be faster than a switch or chained if-else. */
12+
if (token.equals("+")) {
13+
stack.push(second + first);
14+
} else if (token.equals("-")) {
15+
stack.push(second - first);
16+
} else if (token.equals("*")) {
17+
stack.push(second * first);
18+
} else if (token.equals("/")) {
19+
stack.push(second / first);
20+
}
21+
22+
} else {
23+
stack.push(Integer.parseInt(token));
24+
}
25+
}
26+
return stack.peek();
27+
}
28+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import operator
2+
3+
class Solution:
4+
def evalRPN(self, tokens: list[str]) -> int:
5+
6+
ops = {
7+
'+': operator.add,
8+
'-': operator.sub,
9+
'*': operator.mul,
10+
'/': operator.truediv,
11+
}
12+
13+
stack = []
14+
for token in tokens:
15+
if token in "+-*/":
16+
first, second = stack.pop(), stack.pop()
17+
if token != "/":
18+
stack.append(ops[token](second, first))
19+
else:
20+
stack.append(int(second / first))
21+
else:
22+
stack.append(int(token))
23+
return stack[0]

0 commit comments

Comments
 (0)