-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0150_evaluate_reverse_polish_notation.html
More file actions
389 lines (332 loc) · 14.7 KB
/
0150_evaluate_reverse_polish_notation.html
File metadata and controls
389 lines (332 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 150: Evaluate Reverse Polish Notation - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#150</span> Evaluate Reverse Polish Notation</h1>
<p>Evaluate the value of an arithmetic expression in Reverse Polish Notation (postfix notation). Valid operators are +, -, *, and /.</p>
<div class="problem-meta">
<span class="meta-tag">📚 Stack</span>
<span class="meta-tag">🔢 Math</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0150_evaluate_reverse_polish_notation/0150_evaluate_reverse_polish_notation.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>RPN (Reverse Polish Notation) puts operators AFTER operands. Here's how to evaluate it:</p>
<ul>
<li><strong>See a number?</strong> Push it onto the stack</li>
<li><strong>See an operator?</strong> Pop two numbers, apply the operator, push the result</li>
<li><strong>Important:</strong> The SECOND popped value is the LEFT operand (a op b, not b op a)</li>
<li><strong>At the end:</strong> Stack has exactly one element - the answer!</li>
</ul>
<p><strong>Example:</strong> "2 1 +" means 2 + 1 = 3. "3 4 *" means 3 * 4 = 12.</p>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<select id="exampleSelect" style="padding: 8px; border-radius: 5px; border: 2px solid #ddd;">
<option value="0">["2","1","+","3","*"] = 9</option>
<option value="1">["4","13","5","/","+"] = 6</option>
<option value="2">["4","3","-"] = 1</option>
</select>
<button class="btn btn-primary" onclick="loadExample()">Load</button>
<button class="btn btn-primary" onclick="step()">Step</button>
<button class="btn btn-success" onclick="autoRun()">Auto Run</button>
<button class="btn" style="background: #607d8b; color: white;" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Click Step to evaluate the expression token by token
</div>
<div style="margin-top: 20px;">
<h4 style="margin-bottom: 10px;">📝 Tokens</h4>
<div id="tokensContainer" style="display: flex; gap: 8px; flex-wrap: wrap; padding: 15px; background: #f5f5f5; border-radius: 12px;">
</div>
</div>
<div style="display: flex; gap: 30px; flex-wrap: wrap; margin-top: 20px;">
<div style="flex: 1; min-width: 200px;">
<h4 style="margin-bottom: 10px;">📚 Stack</h4>
<div id="stackContainer" style="display: flex; flex-direction: column-reverse; gap: 5px; padding: 20px; background: #e3f2fd; border-radius: 12px; min-height: 200px;">
<span style="color: #999; text-align: center;">Empty</span>
</div>
</div>
<div style="flex: 1; min-width: 250px;">
<h4 style="margin-bottom: 10px;">🧮 Current Operation</h4>
<div id="operationContainer" style="padding: 20px; background: #fff3e0; border-radius: 12px; min-height: 150px; text-align: center;">
<span style="color: #999;">-</span>
</div>
<h4 style="margin-top: 20px; margin-bottom: 10px;">✅ Final Result</h4>
<div id="resultContainer" style="padding: 20px; background: #e8f5e9; border-radius: 12px; text-align: center; font-size: 2em; font-weight: bold; color: #4caf50;">
-
</div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Evaluate Reverse Polish Notation
Problem from LeetCode: https://leetcode.com/problems/evaluate-reverse-polish-notation/
Description:
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 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 to a result, and there will not be any division by zero operation.
Example 1:
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
"""
class Solution:
def eval_r_p_n(self, tokens: List[str]) -> int:
"""
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Args:
tokens: List of tokens in Reverse Polish Notation
Returns:
int: Result of the evaluated expression
"""
stack = []
for token in tokens:
if self.is_operator(token):
b = stack.pop()
a = stack.pop()
result = self.apply_operator(token, a, b)
stack.append(result)
else:
stack.append(int(token))
return stack[0]
def is_operator(self, token: str) -> bool:
"""
Check if a token is an operator.
Args:
token: Token to check
Returns:
bool: True if token is an operator, False otherwise
"""
return token in ['+', '-', '*', '/']
def apply_operator(self, operator: str, a: int, b: int) -> int:
"""
Apply an arithmetic operator to two operands.
Args:
operator: Arithmetic operator (+, -, *, /)
a: First operand
b: Second operand
Returns:
int: Result of the operation a operator b
"""
if operator == '+':
return a + b
elif operator == '-':
return a - b
elif operator == '*':
return a * b
elif operator == '/':
return int(a / b)
else:
raise ValueError('Invalid operator')
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
tokens1 = ["2", "1", "+", "3", "*"]
result1 = solution.eval_r_p_n(tokens1)
print(f"Example 1: {tokens1} -> {result1}") # Expected output: 9
# Example 2
tokens2 = ["4", "13", "5", "/", "+"]
result2 = solution.eval_r_p_n(tokens2)
print(f"Example 2: {tokens2} -> {result2}") # Expected output: 6
# Example 3
tokens3 = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
result3 = solution.eval_r_p_n(tokens3)
print(f"Example 3: Result = {result3}") # Expected output: 22
# Additional example with negative numbers
tokens4 = ["4", "3", "-"]
result4 = solution.eval_r_p_n(tokens4)
print(f"Example 4: {tokens4} -> {result4}") # Expected output: 1
</pre>
</div>
</div>
</div>
<script>
const examples = [
["2", "1", "+", "3", "*"],
["4", "13", "5", "/", "+"],
["4", "3", "-"]
];
let tokens = [...examples[0]];
let stack = [];
let currentIdx = 0;
let done = false;
let isRunning = false;
function loadExample() {
const idx = parseInt(document.getElementById('exampleSelect').value);
tokens = [...examples[idx]];
reset();
}
function isOperator(token) {
return ['+', '-', '*', '/'].includes(token);
}
function renderTokens() {
const container = document.getElementById('tokensContainer');
container.innerHTML = tokens.map((t, i) => {
let bgColor = '#fff';
let borderColor = '#ddd';
let textColor = '#333';
if (i < currentIdx) {
bgColor = '#e0e0e0';
textColor = '#999';
} else if (i === currentIdx) {
bgColor = isOperator(t) ? '#ff9800' : '#667eea';
borderColor = isOperator(t) ? '#f57c00' : '#5a6fd6';
textColor = 'white';
}
return `
<div style="padding: 12px 18px; background: ${bgColor}; border: 2px solid ${borderColor};
border-radius: 8px; font-weight: bold; font-size: 1.2em; color: ${textColor};
min-width: 40px; text-align: center;">
${t}
${i === currentIdx ? '<div style="font-size: 0.6em; margin-top: 2px;">▲</div>' : ''}
</div>
`;
}).join('');
}
function renderStack() {
const container = document.getElementById('stackContainer');
if (stack.length === 0) {
container.innerHTML = '<span style="color: #999; text-align: center;">Empty</span>';
return;
}
container.innerHTML = stack.map((val, i) => {
const isTop = i === stack.length - 1;
return `
<div style="padding: 12px 20px; background: ${isTop ? '#667eea' : '#fff'};
border: 2px solid ${isTop ? '#5a6fd6' : '#90caf9'}; border-radius: 8px;
font-weight: bold; font-size: 1.2em; color: ${isTop ? 'white' : '#333'};
text-align: center;">
${val}
${isTop ? '<span style="margin-left: 10px; font-size: 0.8em;">← TOP</span>' : ''}
</div>
`;
}).reverse().join('');
}
function renderOperation(op, a, b, result) {
const container = document.getElementById('operationContainer');
if (!op) {
container.innerHTML = '<span style="color: #999;">-</span>';
return;
}
const opSymbol = op === '*' ? '×' : op === '/' ? '÷' : op;
container.innerHTML = `
<div style="font-size: 1.5em; color: #666;">
<span style="color: #667eea; font-weight: bold;">${a}</span>
<span style="color: #ff9800; margin: 0 10px;">${opSymbol}</span>
<span style="color: #667eea; font-weight: bold;">${b}</span>
</div>
<div style="font-size: 2em; margin: 10px 0;">=</div>
<div style="font-size: 2em; color: #4caf50; font-weight: bold;">${result}
</div>
`;
}
function step() {
if (done) {
document.getElementById('statusMessage').textContent =
`Done! Final answer: ${stack[0]}`;
return;
}
if (currentIdx >= tokens.length) {
done = true;
document.getElementById('resultContainer').textContent = stack[0];
document.getElementById('statusMessage').textContent =
`Complete! The expression evaluates to ${stack[0]}`;
return;
}
const token = tokens[currentIdx];
if (isOperator(token)) {
const b = stack.pop();
const a = stack.pop();
let result;
switch (token) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/': result = Math.trunc(a / b); break;
}
stack.push(result);
renderOperation(token, a, b, result);
document.getElementById('statusMessage').textContent =
`Operator "${token}": Pop ${b} and ${a}, compute ${a} ${token} ${b} = ${result}, push ${result}`;
} else {
const num = parseInt(token);
stack.push(num);
renderOperation(null);
document.getElementById('statusMessage').textContent =
`Number "${token}": Push ${num} onto stack`;
}
currentIdx++;
renderTokens();
renderStack();
if (currentIdx >= tokens.length) {
document.getElementById('resultContainer').textContent = stack[0];
}
}
function autoRun() {
if (isRunning) return;
isRunning = true;
const interval = setInterval(() => {
if (done || currentIdx >= tokens.length) {
clearInterval(interval);
isRunning = false;
if (stack.length > 0) {
document.getElementById('resultContainer').textContent = stack[0];
document.getElementById('statusMessage').textContent =
`Complete! The expression evaluates to ${stack[0]}`;
}
done = true;
return;
}
step();
}, 1000);
}
function reset() {
stack = [];
currentIdx = 0;
done = false;
isRunning = false;
document.getElementById('statusMessage').textContent =
'Click Step to evaluate the expression token by token';
document.getElementById('resultContainer').textContent = '-';
renderTokens();
renderStack();
renderOperation(null);
}
reset();
</script>
</body>
</html>