-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0239_sliding_window_maximum.html
More file actions
338 lines (291 loc) · 12 KB
/
0239_sliding_window_maximum.html
File metadata and controls
338 lines (291 loc) · 12 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sliding Window Maximum - LeetCode 239</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">#239</span> Sliding Window Maximum</h1>
<p>Given an array and a window size k, slide a window across the array and return the maximum value in each window position. Uses a monotonic deque for O(n) efficiency!</p>
<div class="problem-meta">
<span class="meta-tag">🪟 Sliding Window</span>
<span class="meta-tag">📚 Monotonic Deque</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <a href="../python/0239_sliding_window_maximum/0239_sliding_window_maximum.py">0239_sliding_window_maximum.py</a>
</div>
</div>
<div class="explanation-panel">
<h4>💡 How It Works (Layman's Terms)</h4>
<ul>
<li><strong>Problem:</strong> Find the maximum in every window of size k as it slides across</li>
<li><strong>Naive approach:</strong> Check all k elements for each window → O(n×k)</li>
<li><strong>Smart approach:</strong> Use a "monotonic deque" → O(n)</li>
<li><strong>Monotonic Deque:</strong> Keeps elements in decreasing order. Front is always the max!</li>
<li><strong>Key insight:</strong> If a new element is bigger than previous ones, those smaller ones can never be the max (they'll leave the window before the new element)</li>
<li><strong>Remove from back:</strong> Pop smaller elements from deque back</li>
<li><strong>Remove from front:</strong> Pop elements outside the current window</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="info-box">
Window Size (k) = 3
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to see how the monotonic deque finds maximums
</div>
<div class="array-section">
<div class="array-label">Array (nums):</div>
<div class="array-container" id="arrayContainer"></div>
</div>
<div class="array-section">
<div class="array-label">Deque (stores indices, front = max):</div>
<div class="queue-container" id="dequeContainer" style="min-height: 60px;"></div>
</div>
<div class="array-section">
<div class="array-label">Result (maximums):</div>
<div class="array-container" id="resultContainer"></div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
from collections import deque
"""
LeetCode 239: Sliding Window Maximum
Problem from LeetCode: https://leetcode.com/problems/sliding-window-maximum/
You are given an array of integers nums, there is a sliding window of size k which
is moving from the very left of the array to the very right. You can only see the
k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
- 1 <= k <= nums.length
"""
class Solution:
def max_sliding_window(self, nums: List[int], k: int) ->List[int]:
"""
Return the maximum element in each sliding window of size k.
Args:
nums: Array of integers
k: Size of the sliding window
Returns:
List[int]: Maximum elements in each sliding window
"""
if not nums or k <= 0:
return []
n = len(nums)
result = []
dq = deque()
for i in range(n):
while dq and dq[0] < i - k + 1:
dq.popleft()
while dq and nums[dq[-1]] < nums[i]:
dq.pop()
dq.append(i)
if i >= k - 1:
result.append(nums[dq[0]])
return result
def max_sliding_window_naive(self, nums: List[int], k: int) ->List[int]:
"""
Return the maximum element in each sliding window using a naive approach.
Time complexity: O(n*k)
Args:
nums: Array of integers
k: Size of the sliding window
Returns:
List[int]: Maximum elements in each sliding window
"""
n = len(nums)
if n == 0 or k <= 0:
return []
result = []
for i in range(n - k + 1):
max_val = max(nums[i:i + k])
result.append(max_val)
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
nums = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
result = solution.max_sliding_window(nums, k)
print(result) # Output: [3, 3, 5, 5, 6, 7]
nums = [1]
k = 1
result = solution.max_sliding_window(nums, k)
print(result) # Output: [1]
</pre>
</div>
</div>
</div>
<script>
const nums = [1, 3, -1, -3, 5, 3, 6, 7];
const k = 3;
let deque = []; // stores indices
let result = [];
let currentIndex = 0;
let phase = 'init';
let autoInterval = null;
function init() {
renderArray();
renderDeque();
renderResult();
}
function renderArray() {
const container = document.getElementById('arrayContainer');
container.innerHTML = '';
nums.forEach((num, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `num-${idx}`;
box.innerHTML = `${num}<span class="index-label">[${idx}]</span>`;
// Highlight current window
if (phase !== 'init' && idx >= Math.max(0, currentIndex - k + 1) && idx <= currentIndex) {
box.classList.add('current');
}
if (idx === currentIndex && phase !== 'init' && phase !== 'done') {
box.classList.add('highlight');
}
container.appendChild(box);
});
}
function renderDeque() {
const container = document.getElementById('dequeContainer');
container.innerHTML = '';
if (deque.length === 0) {
container.innerHTML = '<span style="color: #999; padding: 10px;">Empty</span>';
return;
}
deque.forEach((idx, pos) => {
const item = document.createElement('div');
item.className = 'queue-item';
if (pos === 0) {
item.style.background = 'linear-gradient(135deg, #4caf50 0%, #8bc34a 100%)';
}
item.innerHTML = `${nums[idx]}<br><small>[${idx}]</small>`;
container.appendChild(item);
});
}
function renderResult() {
const container = document.getElementById('resultContainer');
container.innerHTML = '';
result.forEach((val, idx) => {
const box = document.createElement('div');
box.className = 'array-box complete';
box.innerHTML = `${val}<span class="index-label">[${idx}]</span>`;
container.appendChild(box);
});
if (result.length === 0) {
container.innerHTML = '<span style="color: #999;">Results will appear here...</span>';
}
}
function step() {
if (phase === 'init') {
phase = 'processing';
currentIndex = 0;
document.getElementById('statusMessage').textContent = 'Starting to process array with monotonic deque...';
}
if (phase === 'processing') {
if (currentIndex >= nums.length) {
phase = 'done';
document.getElementById('statusMessage').textContent =
`✅ Done! Maximum in each window: [${result.join(', ')}]`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
renderArray();
return;
}
let action = '';
// Remove elements outside window
while (deque.length > 0 && deque[0] < currentIndex - k + 1) {
const removed = deque.shift();
action += `Remove ${nums[removed]} (index ${removed}) - outside window. `;
}
// Remove smaller elements from back
while (deque.length > 0 && nums[deque[deque.length - 1]] < nums[currentIndex]) {
const removed = deque.pop();
action += `Pop ${nums[removed]} (smaller than ${nums[currentIndex]}). `;
}
// Add current
deque.push(currentIndex);
action += `Add ${nums[currentIndex]} at index ${currentIndex}. `;
// If window is full, record max
if (currentIndex >= k - 1) {
result.push(nums[deque[0]]);
action += `Window full! Max = ${nums[deque[0]]}`;
} else {
action += `Window not yet full (need ${k} elements)`;
}
document.getElementById('statusMessage').textContent = action;
renderArray();
renderDeque();
renderResult();
currentIndex++;
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (phase === 'done') {
stopAuto();
} else {
step();
}
}, 1500);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
phase = 'init';
currentIndex = 0;
deque = [];
result = [];
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').textContent =
'Click "Step" or "Auto Run" to see how the monotonic deque finds maximums';
init();
}
init();
</script>
</body>
</html>