-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0716_max_stack.html
More file actions
530 lines (455 loc) · 19.8 KB
/
0716_max_stack.html
File metadata and controls
530 lines (455 loc) · 19.8 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 716: Max 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">#716</span> Max Stack</h1>
<p>Design a max stack that supports push, pop, top, peekMax, and popMax operations in O(log n) time.</p>
<div class="problem-meta">
<span class="meta-tag">📦 Stack</span>
<span class="meta-tag">🌳 Heap</span>
<span class="meta-tag">⏱️ O(log n) ops</span>
<span class="meta-tag">💾 O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0716_max_stack/0716_max_stack.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Use a <strong>Doubly Linked List + Max Heap + Set</strong>:</p>
<ul>
<li><strong>Linked List:</strong> Stack order (push/pop from tail)</li>
<li><strong>Max Heap:</strong> Track maximum values with node IDs</li>
<li><strong>Removed Set:</strong> Mark lazy-deleted items</li>
<li><strong>Lazy deletion:</strong> Clean up heap when accessing max</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<input type="number" id="inputValue" value="5" style="width: 60px; padding: 8px; border-radius: 6px; border: 1px solid #ddd;">
<button class="btn btn-primary" onclick="push()">Push</button>
<button class="btn btn-warning" onclick="pop()">Pop</button>
<button class="btn" onclick="getTop()">Top</button>
<button class="btn" style="background: #9c27b0; color: white;" onclick="peekMax()">PeekMax</button>
<button class="btn" style="background: #f44336; color: white;" onclick="popMax()">PopMax</button>
<button class="btn" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Perform operations on the Max Stack
</div>
<div style="display: flex; gap: 20px; flex-wrap: wrap; margin-top: 20px;">
<div style="flex: 1; min-width: 200px;">
<h4>📚 Stack (Linked List)</h4>
<svg id="stackViz" width="100%" height="300"></svg>
</div>
<div style="flex: 1; min-width: 200px;">
<h4>🔺 Max Heap</h4>
<div id="heapDisplay" style="padding: 15px; background: #f3e5f5; border-radius: 12px; min-height: 200px;"></div>
</div>
<div style="flex: 1; min-width: 180px;">
<h4>📊 Current State</h4>
<div id="stateDisplay" style="padding: 15px; background: #e8f5e9; border-radius: 12px;">
<div style="margin: 10px 0; padding: 15px; background: white; border-radius: 8px; text-align: center;">
<div style="font-size: 12px; color: #666;">Top</div>
<div id="topValue" style="font-size: 24px; font-weight: bold; color: #2196f3;">-</div>
</div>
<div style="margin: 10px 0; padding: 15px; background: white; border-radius: 8px; text-align: center;">
<div style="font-size: 12px; color: #666;">Max</div>
<div id="maxValue" style="font-size: 24px; font-weight: bold; color: #9c27b0;">-</div>
</div>
<div style="margin: 10px 0; padding: 15px; background: white; border-radius: 8px; text-align: center;">
<div style="font-size: 12px; color: #666;">Size</div>
<div id="sizeValue" style="font-size: 24px; font-weight: bold; color: #4caf50;">0</div>
</div>
</div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Max Stack
Problem from LeetCode: https://leetcode.com/problems/max-stack/
Description:
Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.
Implement the MaxStack class:
- MaxStack() Initializes the stack object.
- void push(int x) Pushes element x onto the stack.
- int pop() Removes the element on top of the stack and returns it.
- int top() Gets the element on the top of the stack without removing it.
- int peekMax() Retrieves the maximum element in the stack without removing it.
- int popMax() Retrieves the maximum element in the stack and removes it. If there are multiple instances of the maximum, only remove the top-most one.
Example 1:
Input:
["MaxStack", "push", "push", "push", "top", "popMax", "top", "peekMax", "pop", "top"]
[[], [5], [1], [5], [], [], [], [], [], []]
Output:
[null, null, null, null, 5, 5, 1, 5, 1, 5]
Explanation:
MaxStack stk = new MaxStack();
stk.push(5); // [5] the top of the stack and the maximum number is 5.
stk.push(1); // [5, 1] the top of the stack is 1, but the maximum is 5.
stk.push(5); // [5, 1, 5] the top of the stack is 5, which is also the maximum.
stk.top(); // return 5, [5, 1, 5] the stack did not change.
stk.popMax(); // return 5, [5, 1] the stack decreased, and the top is now the element 1.
stk.top(); // return 1, [5, 1] the stack did not change.
stk.peekMax(); // return 5, [5, 1] the stack did not change.
stk.pop(); // return 1, [5] the top of the stack is now 5.
stk.top(); // return 5, [5] the stack did not change.
"""
class MaxStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
self.max_stack = []
def push(self, x: int) ->None:
"""
Push element x onto stack.
Args:
x: The element to push
"""
max_val = x if not self.max_stack else max(self.max_stack[-1], x)
self.stack.append(x)
self.max_stack.append(max_val)
def pop(self) ->int:
"""
Remove the top element of the stack and return it.
Returns:
int: The top element of the stack
"""
self.max_stack.pop()
return self.stack.pop()
def top(self) ->int:
"""
Get the top element of the stack.
Returns:
int: The top element of the stack
"""
return self.stack[-1]
def peek_max(self) ->int:
"""
Retrieve the maximum element in the stack.
Returns:
int: The maximum element in the stack
"""
return self.max_stack[-1]
def pop_max(self) ->int:
"""
Remove the maximum element in the stack and return it.
Returns:
int: The maximum element in the stack
"""
max_val = self.peek_max()
buffer = []
while self.top() != max_val:
buffer.append(self.pop())
self.pop()
while buffer:
self.push(buffer.pop())
return max_val
class MaxStackEfficient:
class Node:
def __init__(self, val):
self.val = val
self.prev = None
self.next = None
def __init__(self):
"""
Initialize your data structure here.
This implementation uses a doubly linked list and a dictionary for O(1) operations.
"""
self.head = self.Node(0)
self.tail = self.Node(0)
self.head.next = self.tail
self.tail.prev = self.head
self.val_to_nodes = {}
def _add_node(self, node):
"""Add a node right before the tail."""
prev = self.tail.prev
prev.next = node
node.prev = prev
node.next = self.tail
self.tail.prev = node
def _remove_node(self, node):
"""Remove a node from the doubly linked list."""
prev, nxt = node.prev, node.next
prev.next = nxt
nxt.prev = prev
def push(self, x: int) ->None:
"""Push element x onto stack."""
node = self.Node(x)
self._add_node(node)
if x not in self.val_to_nodes:
self.val_to_nodes[x] = []
self.val_to_nodes[x].append(node)
def pop(self) ->int:
"""Remove the top element of the stack and return it."""
if self.head.next == self.tail:
return -1
node = self.tail.prev
self._remove_node(node)
self.val_to_nodes[node.val].remove(node)
if not self.val_to_nodes[node.val]:
del self.val_to_nodes[node.val]
return node.val
def top(self) ->int:
"""Get the top element of the stack."""
if self.head.next == self.tail:
return -1
return self.tail.prev.val
def peek_max(self) ->int:
"""Retrieve the maximum element in the stack."""
if not self.val_to_nodes:
return -1
return max(self.val_to_nodes.keys())
def pop_max(self) ->int:
"""Remove the maximum element in the stack and return it."""
if not self.val_to_nodes:
return -1
max_val = max(self.val_to_nodes.keys())
node = self.val_to_nodes[max_val][-1]
self._remove_node(node)
self.val_to_nodes[max_val].remove(node)
if not self.val_to_nodes[max_val]:
del self.val_to_nodes[max_val]
return max_val
if __name__ == '__main__':
# Example usage based on LeetCode sample
max_stack = MaxStack()
# Push elements
max_stack.push(5)
max_stack.push(1)
max_stack.push(5)
# Test operations
print("Top element:", max_stack.top()) # Expected: 5
print("Pop max element:", max_stack.pop_max()) # Expected: 5
print("Top element after popMax:", max_stack.top()) # Expected: 1
print("Peek max element:", max_stack.peek_max()) # Expected: 5
print("Pop element:", max_stack.pop()) # Expected: 1
print("Top element after pop:", max_stack.top()) # Expected: 5
# Test the efficient implementation
print("\nTesting efficient implementation:")
max_stack_efficient = MaxStackEfficient()
# Push elements
max_stack_efficient.push(5)
max_stack_efficient.push(1)
max_stack_efficient.push(5)
# Test operations
print("Top element:", max_stack_efficient.top()) # Expected: 5
print("Pop max element:", max_stack_efficient.pop_max()) # Expected: 5
print("Top element after popMax:", max_stack_efficient.top()) # Expected: 1
print("Peek max element:", max_stack_efficient.peek_max()) # Expected: 5
print("Pop element:", max_stack_efficient.pop()) # Expected: 1
print("Top element after pop:", max_stack_efficient.top()) # Expected: 5
</pre>
</div>
</div>
</div>
<script>
// Max Stack implementation
class MaxStack {
constructor() {
this.stack = []; // [{value, id}]
this.heap = []; // [{value, id}] as max heap
this.removed = new Set();
this.nextId = 0;
}
push(x) {
const id = this.nextId++;
this.stack.push({ value: x, id });
this.heap.push({ value: x, id });
this.heap.sort((a, b) => b.value - a.value || b.id - a.id);
}
pop() {
this._cleanStack();
if (this.stack.length === 0) return null;
const item = this.stack.pop();
this.removed.add(item.id);
return item.value;
}
top() {
this._cleanStack();
return this.stack.length > 0 ? this.stack[this.stack.length - 1].value : null;
}
peekMax() {
this._cleanHeap();
return this.heap.length > 0 ? this.heap[0].value : null;
}
popMax() {
this._cleanHeap();
if (this.heap.length === 0) return null;
const item = this.heap.shift();
this.removed.add(item.id);
return item.value;
}
_cleanStack() {
while (this.stack.length > 0 && this.removed.has(this.stack[this.stack.length - 1].id)) {
this.stack.pop();
}
}
_cleanHeap() {
while (this.heap.length > 0 && this.removed.has(this.heap[0].id)) {
this.heap.shift();
}
}
getActiveStack() {
return this.stack.filter(item => !this.removed.has(item.id));
}
getActiveHeap() {
return this.heap.filter(item => !this.removed.has(item.id));
}
}
let maxStack = new MaxStack();
let highlightId = null;
let highlightType = null;
function render() {
// Draw stack
const svg = d3.select("#stackViz");
svg.selectAll("*").remove();
const container = svg.node().parentElement;
const width = container.clientWidth;
const height = 300;
svg.attr("viewBox", `0 0 ${width} ${height}`);
const activeStack = maxStack.getActiveStack();
const boxHeight = 40;
const boxWidth = 80;
const startX = width / 2 - boxWidth / 2;
const startY = height - 30;
activeStack.forEach((item, i) => {
const y = startY - (i + 1) * boxHeight;
const isHighlight = highlightId === item.id;
const isMax = maxStack.peekMax() === item.value &&
item.id === maxStack.getActiveHeap().find(h => h.value === item.value)?.id;
svg.append("rect")
.attr("x", startX).attr("y", y)
.attr("width", boxWidth).attr("height", boxHeight - 5)
.attr("fill", isHighlight ? '#ff9800' : (isMax ? '#9c27b0' : '#667eea'))
.attr("stroke", isHighlight ? '#e65100' : '#5a6fd6')
.attr("stroke-width", isHighlight ? 3 : 2)
.attr("rx", 6);
svg.append("text")
.attr("x", startX + boxWidth / 2).attr("y", y + boxHeight / 2 + 2)
.attr("text-anchor", "middle")
.attr("fill", "white").attr("font-weight", "bold").attr("font-size", "18px")
.text(item.value);
if (i === activeStack.length - 1) {
svg.append("text")
.attr("x", startX - 10).attr("y", y + boxHeight / 2 + 2)
.attr("text-anchor", "end")
.attr("fill", "#666").attr("font-size", "12px")
.text("TOP →");
}
});
if (activeStack.length === 0) {
svg.append("text")
.attr("x", width / 2).attr("y", height / 2)
.attr("text-anchor", "middle")
.attr("fill", "#999").attr("font-size", "16px")
.text("Stack is empty");
}
// Base
svg.append("line")
.attr("x1", startX - 20).attr("y1", startY)
.attr("x2", startX + boxWidth + 20).attr("y2", startY)
.attr("stroke", "#333").attr("stroke-width", 3);
// Draw heap
const heapContainer = document.getElementById('heapDisplay');
const activeHeap = maxStack.getActiveHeap();
if (activeHeap.length === 0) {
heapContainer.innerHTML = '<span style="color: #999;">Heap is empty</span>';
} else {
heapContainer.innerHTML = activeHeap.map((item, i) => {
const isHighlight = highlightId === item.id;
const bgColor = isHighlight ? '#ff9800' : (i === 0 ? '#9c27b0' : '#e1bee7');
const textColor = (i === 0 || isHighlight) ? 'white' : '#4a148c';
return `<div style="display: inline-block; margin: 5px; padding: 10px 15px; background: ${bgColor};
color: ${textColor}; border-radius: 20px; font-weight: bold;">
${item.value}${i === 0 ? ' (MAX)' : ''}
</div>`;
}).join('');
}
// Update state
const top = maxStack.top();
const max = maxStack.peekMax();
document.getElementById('topValue').textContent = top !== null ? top : '-';
document.getElementById('maxValue').textContent = max !== null ? max : '-';
document.getElementById('sizeValue').textContent = activeStack.length;
}
function push() {
const value = parseInt(document.getElementById('inputValue').value) || 0;
maxStack.push(value);
document.getElementById('statusMessage').textContent = `Pushed ${value} to stack`;
render();
}
function pop() {
const value = maxStack.pop();
if (value !== null) {
document.getElementById('statusMessage').textContent = `Popped ${value} from stack`;
} else {
document.getElementById('statusMessage').textContent = 'Stack is empty!';
}
render();
}
function getTop() {
const value = maxStack.top();
if (value !== null) {
document.getElementById('statusMessage').textContent = `Top element: ${value}`;
const activeStack = maxStack.getActiveStack();
if (activeStack.length > 0) {
highlightId = activeStack[activeStack.length - 1].id;
render();
setTimeout(() => { highlightId = null; render(); }, 1000);
}
} else {
document.getElementById('statusMessage').textContent = 'Stack is empty!';
}
}
function peekMax() {
const value = maxStack.peekMax();
if (value !== null) {
document.getElementById('statusMessage').textContent = `Max element: ${value}`;
const activeHeap = maxStack.getActiveHeap();
if (activeHeap.length > 0) {
highlightId = activeHeap[0].id;
render();
setTimeout(() => { highlightId = null; render(); }, 1000);
}
} else {
document.getElementById('statusMessage').textContent = 'Stack is empty!';
}
}
function popMax() {
const value = maxStack.popMax();
if (value !== null) {
document.getElementById('statusMessage').textContent = `Popped max element: ${value}`;
} else {
document.getElementById('statusMessage').textContent = 'Stack is empty!';
}
render();
}
function reset() {
maxStack = new MaxStack();
highlightId = null;
document.getElementById('statusMessage').textContent = 'Max Stack reset';
render();
}
// Initialize with some values
[3, 1, 5, 2].forEach(v => maxStack.push(v));
render();
window.addEventListener('resize', render);
</script>
</body>
</html>