-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0155_min_stack.html
More file actions
335 lines (273 loc) · 12.3 KB
/
0155_min_stack.html
File metadata and controls
335 lines (273 loc) · 12.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 155: Min Stack - 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">#155</span> Min Stack</h1>
<p>Design a stack that supports push, pop, top, and retrieving the minimum element in O(1) time.</p>
<div class="problem-meta">
<span class="meta-tag">📚 Stack</span>
<span class="meta-tag">🎨 Design</span>
<span class="meta-tag">⏱️ O(1) all ops</span>
<span class="meta-tag">💾 O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0155_min_stack/0155_min_stack.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>The trick: <strong>store the minimum value with each node</strong>!</p>
<ul>
<li><strong>Each node stores:</strong> its value AND the minimum of all values below it</li>
<li><strong>On push:</strong> new min = min(new value, previous min)</li>
<li><strong>On pop:</strong> min automatically updates (stored in next node)</li>
<li><strong>getMin:</strong> Just read the min from the top node - O(1)!</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<input type="number" id="pushValue" placeholder="Value" style="width: 80px; padding: 8px; border-radius: 5px; border: 2px solid #ddd;">
<button class="btn btn-primary" onclick="pushVal()">Push</button>
<button class="btn btn-warning" onclick="popVal()">Pop</button>
<button class="btn btn-success" onclick="getTop()">Top</button>
<button class="btn" style="background: #9c27b0; color: white;" onclick="getMinVal()">getMin</button>
<button class="btn" style="background: #607d8b; color: white;" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Try push, pop, top, or getMin operations!
</div>
<div style="display: flex; gap: 30px; flex-wrap: wrap; margin-top: 20px;">
<div style="flex: 1; min-width: 300px;">
<h4 style="margin-bottom: 10px;">📚 Stack (with min tracking)</h4>
<div id="stackContainer" style="display: flex; flex-direction: column-reverse; gap: 5px; padding: 20px; background: #f5f5f5; border-radius: 12px; min-height: 300px;">
<div style="color: #999; text-align: center;">Empty Stack</div>
</div>
</div>
<div style="flex: 1; min-width: 250px;">
<h4 style="margin-bottom: 10px;">📊 Operations Log</h4>
<div id="logContainer" style="padding: 15px; background: #f5f5f5; border-radius: 12px; min-height: 300px; max-height: 300px; overflow-y: auto;">
<div style="color: #999;">No operations yet...</div>
</div>
</div>
</div>
<div class="info-box" style="margin-top: 20px;">
<h4>🔑 Key Insight</h4>
<p>By storing the minimum at each level, we always know the minimum of all elements below (including) that node. When we pop, the new top already has the correct minimum stored!</p>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode 155. Min Stack
Problem from LeetCode: https://leetcode.com/problems/min-stack/
Description:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
- MinStack() initializes the stack object.
- void push(int val) pushes the element val onto the stack.
- void pop() removes the element on the top of the stack.
- int top() gets the top element of the stack.
- int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
- -2^31 <= val <= 2^31 - 1
- Methods pop, top and getMin operations will always be called on non-empty stacks.
- At most 3 * 10^4 calls will be made to push, pop, top, and getMin.
"""
class MinStack:
class Node:
def __init__(self, val, min_val, next_node=None):
self.val = val
self.min = min_val
self.next = next_node
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
def push(self, val: int) ->None:
if not self.head:
self.head = self.Node(val, val)
else:
self.head = self.Node(val, min(val, self.head.min), self.head)
def pop(self) ->None:
self.head = self.head.next
def top(self) ->int:
return self.head.val
def get_min(self) ->int:
return self.head.min
if __name__ == '__main__':
# Example usage based on LeetCode sample
print("Example 1:")
print("Operations: [\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]")
print("Values: [[],[-2],[0],[-3],[],[],[],[]]")
print("Output:")
min_stack = MinStack() # null
print("MinStack() -> null")
min_stack.push(-2) # null
print("push(-2) -> null")
min_stack.push(0) # null
print("push(0) -> null")
min_stack.push(-3) # null
print("push(-3) -> null")
print(f"getMin() -> {min_stack.get_min()}") # return -3
min_stack.pop() # null
print("pop() -> null")
print(f"top() -> {min_stack.top()}") # return 0
print(f"getMin() -> {min_stack.get_min()}") # return -2
</pre>
</div>
</div>
</div>
<script>
let stack = []; // Each element: {val, min}
let logs = [];
function renderStack() {
const container = document.getElementById('stackContainer');
if (stack.length === 0) {
container.innerHTML = '<div style="color: #999; text-align: center;">Empty Stack</div>';
return;
}
container.innerHTML = stack.map((item, i) => {
const isTop = i === stack.length - 1;
return `
<div style="display: flex; align-items: center; padding: 12px 15px;
background: ${isTop ? '#667eea' : '#fff'};
border: 2px solid ${isTop ? '#5a6fd6' : '#ddd'};
border-radius: 8px; color: ${isTop ? 'white' : '#333'};">
<div style="flex: 1;">
<strong>val: ${item.val}</strong>
</div>
<div style="background: ${isTop ? 'rgba(255,255,255,0.2)' : '#e8f5e9'};
padding: 4px 10px; border-radius: 4px; font-size: 0.9em;
color: ${isTop ? 'white' : '#4caf50'};">
min: ${item.min}
</div>
${isTop ? '<span style="margin-left: 10px;">← TOP</span>' : ''}
</div>
`;
}).reverse().join('');
}
function renderLogs() {
const container = document.getElementById('logContainer');
if (logs.length === 0) {
container.innerHTML = '<div style="color: #999;">No operations yet...</div>';
return;
}
container.innerHTML = logs.map((log, i) => `
<div style="padding: 8px; margin-bottom: 5px; background: ${log.color};
border-radius: 5px; font-size: 0.9em;">
<strong>${log.op}:</strong> ${log.msg}
</div>
`).join('');
container.scrollTop = container.scrollHeight;
}
function addLog(op, msg, color = '#e3f2fd') {
logs.push({ op, msg, color });
if (logs.length > 20) logs.shift();
renderLogs();
}
function pushVal() {
const input = document.getElementById('pushValue');
const val = parseInt(input.value);
if (isNaN(val)) {
document.getElementById('statusMessage').textContent = '⚠️ Please enter a valid number';
return;
}
const newMin = stack.length === 0 ? val : Math.min(val, stack[stack.length - 1].min);
stack.push({ val, min: newMin });
document.getElementById('statusMessage').textContent =
`Pushed ${val}. New min at this level: ${newMin}`;
addLog('push', `val=${val}, min=${newMin}`, '#e3f2fd');
input.value = '';
renderStack();
}
function popVal() {
if (stack.length === 0) {
document.getElementById('statusMessage').textContent = '⚠️ Stack is empty!';
return;
}
const popped = stack.pop();
const newMin = stack.length > 0 ? stack[stack.length - 1].min : 'N/A';
document.getElementById('statusMessage').textContent =
`Popped ${popped.val}. ${stack.length > 0 ? 'New min: ' + newMin : 'Stack is now empty.'}`;
addLog('pop', `removed ${popped.val}`, '#fff3e0');
renderStack();
}
function getTop() {
if (stack.length === 0) {
document.getElementById('statusMessage').textContent = '⚠️ Stack is empty!';
return;
}
const top = stack[stack.length - 1].val;
document.getElementById('statusMessage').textContent = `Top element: ${top}`;
addLog('top', `returned ${top}`, '#e8f5e9');
}
function getMinVal() {
if (stack.length === 0) {
document.getElementById('statusMessage').textContent = '⚠️ Stack is empty!';
return;
}
const min = stack[stack.length - 1].min;
document.getElementById('statusMessage').textContent = `Minimum element: ${min} (O(1) lookup!)`;
addLog('getMin', `returned ${min}`, '#f3e5f5');
}
function reset() {
stack = [];
logs = [];
document.getElementById('statusMessage').textContent = 'Stack reset. Try push, pop, top, or getMin!';
renderStack();
renderLogs();
}
// Demo sequence
function runDemo() {
const ops = [
() => { document.getElementById('pushValue').value = -2; pushVal(); },
() => { document.getElementById('pushValue').value = 0; pushVal(); },
() => { document.getElementById('pushValue').value = -3; pushVal(); },
() => getMinVal(),
() => popVal(),
() => getTop(),
() => getMinVal()
];
let i = 0;
const interval = setInterval(() => {
if (i >= ops.length) {
clearInterval(interval);
return;
}
ops[i]();
i++;
}, 1000);
}
renderStack();
renderLogs();
</script>
</body>
</html>