Skip to content

Commit 2e01b7c

Browse files
authored
Merge pull request #1535 from katarianikita2003/main
Create-0150-Evaluate-Reverse-Polish_Notation
2 parents b723d53 + d2bbfd8 commit 2e01b7c

File tree

1 file changed

+238
-0
lines changed

1 file changed

+238
-0
lines changed
Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
1+
---
2+
id: Evaluate-Reverse-Polish_Notation
3+
title: Evaluate-Reverse-Polish_Notation
4+
sidebar_label: Evaluate-Reverse-Polish_Notation
5+
tags:
6+
- Reverse Polish Notation
7+
- Stack
8+
- Evaluation
9+
---
10+
11+
## Problem Description
12+
13+
| Problem Statement | Solution Link | LeetCode Profile |
14+
| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ |
15+
| [Evaluate-Reverse-Polish_Notation](https://leetcode.com/problems/Evaluate-Reverse-Polish_Notation/description/) | [Evaluate-Reverse-Polish_Notation Solution on LeetCode](https://leetcode.com/problems/Evaluate-Reverse-Polish_Notation/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) |
16+
17+
## Problem Description
18+
19+
You are given an array of strings `tokens` that represents an arithmetic expression in Reverse Polish Notation.
20+
21+
Evaluate the expression and return an integer that represents the value of the expression.
22+
23+
Note that:
24+
- The valid operators are '+', '-', '*', and '/'.
25+
- Each operand may be an integer or another expression.
26+
- The division between two integers always truncates toward zero.
27+
- There will not be any division by zero.
28+
- The input represents a valid arithmetic expression in reverse polish notation.
29+
- The answer and all the intermediate calculations can be represented in a 32-bit integer.
30+
31+
### Examples
32+
33+
#### Example 1
34+
**Input**: `tokens = ["2", "1", "+", "3", "*"]`
35+
**Output**: `9`
36+
**Explanation**: ((2 + 1) * 3) = 9
37+
38+
#### Example 2
39+
**Input**: `tokens = ["4", "13", "5", "/", "+"]`
40+
**Output**: `6`
41+
**Explanation**: (4 + (13 / 5)) = 6
42+
43+
#### Example 3
44+
**Input**: `tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]`
45+
**Output**: `22`
46+
**Explanation**:
47+
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
48+
= ((10 * (6 / (12 * -11))) + 17) + 5
49+
= ((10 * (6 / -132)) + 17) + 5
50+
= ((10 * 0) + 17) + 5
51+
= (0 + 17) + 5
52+
= 17 + 5
53+
= 22
54+
55+
## Constraints
56+
57+
- `1 <= tokens.length <= 10^4`
58+
- `tokens[i]` is either an operator: `"+"`, `"-"`, `"*"` or `"/"`, or an integer in the range `[-200, 200]`.
59+
60+
## Approach
61+
62+
1. Initialize an empty stack.
63+
2. Iterate over each token in the `tokens` array:
64+
- If the token is an operand (integer), push it onto the stack.
65+
- If the token is an operator, pop the necessary number of operands from the stack, apply the operator, and push the result back onto the stack.
66+
3. The final result will be the only element left in the stack.
67+
68+
## Solution in different languages:
69+
70+
### Solution in Python
71+
```python
72+
def evalRPN(tokens):
73+
stack = []
74+
for token in tokens:
75+
if token in "+-*/":
76+
b = stack.pop()
77+
a = stack.pop()
78+
if token == '+':
79+
stack.append(a + b)
80+
elif token == '-':
81+
stack.append(a - b)
82+
elif token == '*':
83+
stack.append(a * b)
84+
elif token == '/':
85+
stack.append(int(a / b)) # use int() for truncating towards zero
86+
else:
87+
stack.append(int(token))
88+
return stack[0]
89+
```
90+
91+
### Solution in Java
92+
```java
93+
import java.util.Stack;
94+
95+
class Solution {
96+
public int evalRPN(String[] tokens) {
97+
Stack<Integer> stack = new Stack<>();
98+
for (String token : tokens) {
99+
if ("+-*/".contains(token)) {
100+
int b = stack.pop();
101+
int a = stack.pop();
102+
switch (token) {
103+
case "+":
104+
stack.push(a + b);
105+
break;
106+
case "-":
107+
stack.push(a - b);
108+
break;
109+
case "*":
110+
stack.push(a * b);
111+
break;
112+
case "/":
113+
stack.push(a / b);
114+
break;
115+
}
116+
} else {
117+
stack.push(Integer.parseInt(token));
118+
}
119+
}
120+
return stack.pop();
121+
}
122+
}
123+
```
124+
125+
### Solution in C++
126+
```cpp
127+
#include <vector>
128+
#include <string>
129+
#include <stack>
130+
131+
class Solution {
132+
public:
133+
int evalRPN(std::vector<std::string>& tokens) {
134+
std::stack<int> stack;
135+
for (const std::string& token : tokens) {
136+
if (token == "+" || token == "-" || token == "*" || token == "/") {
137+
int b = stack.top(); stack.pop();
138+
int a = stack.top(); stack.pop();
139+
if (token == "+") stack.push(a + b);
140+
else if (token == "-") stack.push(a - b);
141+
else if (token == "*") stack.push(a * b);
142+
else if (token == "/") stack.push(a / b);
143+
} else {
144+
stack.push(std::stoi(token));
145+
}
146+
}
147+
return stack.top();
148+
}
149+
};
150+
```
151+
152+
### Solution in C
153+
```c
154+
#include <stdio.h>
155+
#include <stdlib.h>
156+
#include <string.h>
157+
158+
#define STACK_SIZE 10000
159+
160+
typedef struct {
161+
int data[STACK_SIZE];
162+
int top;
163+
} Stack;
164+
165+
void init(Stack* s) {
166+
s->top = -1;
167+
}
168+
169+
void push(Stack* s, int value) {
170+
s->data[++s->top] = value;
171+
}
172+
173+
int pop(Stack* s) {
174+
return s->data[s->top--];
175+
}
176+
177+
int evalRPN(char ** tokens, int tokensSize){
178+
Stack stack;
179+
init(&stack);
180+
for (int i = 0; i < tokensSize; i++) {
181+
char *token = tokens[i];
182+
if (strcmp(token, "+") == 0 || strcmp(token, "-") == 0 || strcmp(token, "*") == 0 || strcmp(token, "/") == 0) {
183+
int b = pop(&stack);
184+
int a = pop(&stack);
185+
if (strcmp(token, "+") == 0) push(&stack, a + b);
186+
else if (strcmp(token, "-") == 0) push(&stack, a - b);
187+
else if (strcmp(token, "*") == 0) push(&stack, a * b);
188+
else if (strcmp(token, "/") == 0) push(&stack, a / b);
189+
} else {
190+
push(&stack, atoi(token));
191+
}
192+
}
193+
return pop(&stack);
194+
}
195+
```
196+
197+
### Solution in JavaScript
198+
```js
199+
var evalRPN = function(tokens) {
200+
const stack = [];
201+
for (const token of tokens) {
202+
if ("+-*/".includes(token)) {
203+
const b = stack.pop();
204+
const a = stack.pop();
205+
switch (token) {
206+
case '+':
207+
stack.push(a + b);
208+
break;
209+
case '-':
210+
stack.push(a - b);
211+
break;
212+
case '*':
213+
stack.push(a * b);
214+
break;
215+
case '/':
216+
stack.push(Math.trunc(a / b));
217+
break;
218+
}
219+
} else {
220+
stack.push(Number(token));
221+
}
222+
}
223+
return stack[0];
224+
};
225+
```
226+
227+
### Step-by-step Algorithm
228+
1. Initialize an empty stack.
229+
2. Iterate through each token in the `tokens` list.
230+
3. If the token is an operand (number), push it onto the stack.
231+
4. If the token is an operator, pop two operands from the stack.
232+
- Apply the operator on the two operands.
233+
- Push the result back onto the stack.
234+
5. Continue this process until all tokens are processed.
235+
6. The final result will be the last item remaining in the stack.
236+
237+
### Conclusion
238+
The Reverse Polish Notation evaluation is efficiently handled using a stack. This approach ensures that we can process the expression in a single pass through the tokens, leading to a time complexity of O(n) and a space complexity of O(n) where n is the number of tokens.

0 commit comments

Comments
 (0)