-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0076_minimum_window_substring.html
More file actions
484 lines (401 loc) · 18.7 KB
/
Copy path0076_minimum_window_substring.html
File metadata and controls
484 lines (401 loc) · 18.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 76: Minimum Window Substring - 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">#76</span> Minimum Window Substring</h1>
<p>Given strings s and t, find the minimum window substring in s that contains all characters of t (including duplicates).</p>
<div class="problem-meta">
<span class="meta-tag">🪟 Sliding Window</span>
<span class="meta-tag">📚 HashMap</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(m)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0076_minimum_window_substring/0076_minimum_window_substring.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>A classic <strong>sliding window</strong> problem with two phases:</p>
<ul>
<li><strong>Expand (right pointer):</strong> Keep adding characters until we have all of t</li>
<li><strong>Contract (left pointer):</strong> Once valid, shrink from left to find minimum</li>
<li><strong>Track "formed":</strong> How many unique characters have met their required count</li>
<li><strong>Update answer:</strong> Every time we have a valid window, check if it's smallest</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<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">
Find minimum window in "ADOBECODEBANC" containing "ABC"
</div>
<div class="variable-display" id="variables">
<div class="var-box">
<span class="var-label">left</span>
<span class="var-value" id="varLeft">0</span>
</div>
<div class="var-box">
<span class="var-label">right</span>
<span class="var-value" id="varRight">0</span>
</div>
<div class="var-box">
<span class="var-label">formed</span>
<span class="var-value" id="varFormed">0/3</span>
</div>
<div class="var-box" style="background: #e8f5e9;">
<span class="var-label">Min Window</span>
<span class="var-value" id="varMin" style="color: #4caf50; font-size: 0.8em;">-</span>
</div>
</div>
<div style="margin-top: 20px;">
<h4 style="margin-bottom: 10px;">🔤 String s = "ADOBECODEBANC" | t = "ABC"</h4>
<div id="stringContainer" style="display: flex; gap: 3px; flex-wrap: wrap; padding: 15px; background: #f5f5f5; border-radius: 12px; justify-content: center;">
</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;">📚 Required (from t)</h4>
<div id="requiredContainer" style="display: flex; gap: 10px; flex-wrap: wrap; padding: 15px; background: #fff3e0; border-radius: 12px;">
</div>
</div>
<div style="flex: 1; min-width: 200px;">
<h4 style="margin-bottom: 10px;">🪟 Window Counts</h4>
<div id="windowContainer" style="display: flex; gap: 10px; flex-wrap: wrap; padding: 15px; background: #e3f2fd; border-radius: 12px;">
</div>
</div>
</div>
<div id="resultContainer" style="margin-top: 20px; padding: 20px; background: #e8f5e9; border-radius: 12px; text-align: center;">
<h4>🏆 Best Window Found</h4>
<div id="bestWindow" style="font-size: 1.5em; font-weight: bold; color: #4caf50;">-</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Dict
from collections import Counter
"""
LeetCode Minimum Window Substring
Problem from LeetCode: https://leetcode.com/problems/minimum-window-substring/
Description:
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
The testcases will be generated such that the answer is unique.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string.
"""
class Solution:
def min_window(self, s: str, t: str) -> str:
"""
Find the minimum window substring of s that contains all characters from t.
Uses sliding window technique with character frequency counting.
Args:
s: Source string
t: Target string
Returns:
str: Minimum window substring, or empty string if none exists
"""
if not s or not t:
return ""
# Count required characters in t
required = Counter(t)
required_count = len(required)
# Initialize sliding window variables
left = 0
formed = 0 # Count of characters that have met the required frequency
window_counts = {}
# Initialize minimum window variables
min_len = float('inf')
min_window_start = 0
# Iterate through the string with right pointer
for right in range(len(s)):
# Add current character to window count
char = s[right]
window_counts[char] = window_counts.get(char, 0) + 1
# Check if the current character contributes to forming required characters
if char in required and window_counts[char] == required[char]:
formed += 1
# Try to minimize the window by moving left pointer
while left <= right and formed == required_count:
char = s[left]
# Update minimum window if current window is smaller
window_len = right - left + 1
if window_len < min_len:
min_len = window_len
min_window_start = left
# Remove the leftmost character from the window
window_counts[char] -= 1
# If removing this character breaks the required count
if char in required and window_counts[char] < required[char]:
formed -= 1
# Move left pointer to shrink the window
left += 1
# If no valid window found
if min_len == float('inf'):
return ""
return s[min_window_start:min_window_start + min_len]
def min_window_optimized(self, s: str, t: str) -> str:
"""
Optimized version that only considers characters in t.
Args:
s: Source string
t: Target string
Returns:
str: Minimum window substring, or empty string if none exists
"""
if not s or not t:
return ""
# Dictionary to keep count of characters in t
dict_t = Counter(t)
# Number of unique characters in t
required = len(dict_t)
# Dictionary for window characters
window_counts = {}
# 'formed' keeps track of how many unique characters in t are satisfied
formed = 0
# Answer variables
ans = float('inf'), -1, -1 # window_size, left, right
# Initialize pointers
left = right = 0
while right < len(s):
# Add the rightmost character to the window
char = s[right]
window_counts[char] = window_counts.get(char, 0) + 1
# Check if adding this character contributes to the required count
if char in dict_t and window_counts[char] == dict_t[char]:
formed += 1
# Try to contract the window
while left <= right and formed == required:
char = s[left]
# Update the answer if this window is smaller
if right - left + 1 < ans[0]:
ans = (right - left + 1, left, right)
# Remove the leftmost character from the window
window_counts[char] -= 1
if char in dict_t and window_counts[char] < dict_t[char]:
formed -= 1
left += 1
right += 1
return "" if ans[0] == float('inf') else s[ans[1]:ans[2] + 1]
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1, t1 = "ADOBECODEBANC", "ABC"
result1 = solution.min_window(s1, t1)
print(f"Example 1: s='{s1}', t='{t1}', result='{result1}'") # Expected: "BANC"
# Example 2
s2, t2 = "a", "a"
result2 = solution.min_window(s2, t2)
print(f"Example 2: s='{s2}', t='{t2}', result='{result2}'") # Expected: "a"
# Example 3
s3, t3 = "a", "aa"
result3 = solution.min_window(s3, t3)
print(f"Example 3: s='{s3}', t='{t3}', result='{result3}'") # Expected: ""
# Compare with optimized approach
print("\nUsing optimized approach:")
print(f"Example 1: '{solution.min_window_optimized(s1, t1)}'") # Expected: "BANC"
print(f"Example 2: '{solution.min_window_optimized(s2, t2)}'") # Expected: "a"
print(f"Example 3: '{solution.min_window_optimized(s3, t3)}'") # Expected: ""
</pre>
</div>
</div>
</div>
<script>
const s = "ADOBECODEBANC";
const t = "ABC";
let required = {};
t.split('').forEach(c => required[c] = (required[c] || 0) + 1);
const requiredCount = Object.keys(required).length;
let window_counts = {};
let left = 0;
let right = 0;
let formed = 0;
let minLen = Infinity;
let minStart = 0;
let done = false;
let isRunning = false;
let phase = 'expand'; // 'expand' or 'contract'
function renderString() {
const container = document.getElementById('stringContainer');
container.innerHTML = s.split('').map((char, i) => {
let bgColor = '#fff';
let borderColor = '#ddd';
if (i >= left && i < right) {
bgColor = formed === requiredCount ? '#c8e6c9' : '#bbdefb';
borderColor = formed === requiredCount ? '#a5d6a7' : '#90caf9';
}
if (i === right && !done) {
bgColor = '#ff9800';
borderColor = '#f57c00';
}
if (i === left && phase === 'contract' && !done) {
borderColor = '#f44336';
}
return `
<div style="width: 40px; height: 45px; display: flex; flex-direction: column;
align-items: center; justify-content: center; background: ${bgColor};
border: 3px solid ${borderColor}; border-radius: 6px; font-weight: bold;">
<span style="font-size: 1.2em;">${char}</span>
<span style="font-size: 0.6em; color: #999;">${i}</span>
</div>
`;
}).join('');
}
function renderRequired() {
const container = document.getElementById('requiredContainer');
container.innerHTML = Object.entries(required).map(([char, count]) => {
const windowCount = window_counts[char] || 0;
const satisfied = windowCount >= count;
return `
<div style="padding: 10px 15px; background: ${satisfied ? '#4caf50' : '#ff9800'};
color: white; border-radius: 8px; text-align: center;">
<div style="font-size: 1.2em; font-weight: bold;">${char}</div>
<div style="font-size: 0.8em;">need: ${count}</div>
</div>
`;
}).join('');
}
function renderWindow() {
const container = document.getElementById('windowContainer');
const relevantChars = Object.keys(required);
const entries = relevantChars.map(char => [char, window_counts[char] || 0]);
container.innerHTML = entries.map(([char, count]) => {
const needed = required[char];
const satisfied = count >= needed;
return `
<div style="padding: 10px 15px; background: ${satisfied ? '#4caf50' : '#667eea'};
color: white; border-radius: 8px; text-align: center;">
<div style="font-size: 1.2em; font-weight: bold;">${char}</div>
<div style="font-size: 0.8em;">have: ${count}</div>
</div>
`;
}).join('');
}
function updateVariables() {
document.getElementById('varLeft').textContent = left;
document.getElementById('varRight').textContent = right;
document.getElementById('varFormed').textContent = `${formed}/${requiredCount}`;
document.getElementById('varMin').textContent =
minLen === Infinity ? '-' : `"${s.substring(minStart, minStart + minLen)}" (${minLen})`;
}
function updateBestWindow() {
const container = document.getElementById('bestWindow');
if (minLen === Infinity) {
container.textContent = '-';
} else {
container.textContent = `"${s.substring(minStart, minStart + minLen)}" (length: ${minLen})`;
}
}
function step() {
if (done) {
document.getElementById('statusMessage').textContent =
minLen === Infinity ?
'No valid window found!' :
`Done! Minimum window: "${s.substring(minStart, minStart + minLen)}"`;
return;
}
if (phase === 'expand') {
if (right >= s.length) {
done = true;
document.getElementById('statusMessage').textContent =
`Complete! Answer: "${s.substring(minStart, minStart + minLen)}"`;
return;
}
const char = s[right];
window_counts[char] = (window_counts[char] || 0) + 1;
if (char in required && window_counts[char] === required[char]) {
formed++;
document.getElementById('statusMessage').textContent =
`Added '${char}'. Now have enough '${char}'s! (formed: ${formed}/${requiredCount})`;
} else {
document.getElementById('statusMessage').textContent =
`Added '${char}' to window. (formed: ${formed}/${requiredCount})`;
}
right++;
if (formed === requiredCount) {
phase = 'contract';
}
} else if (phase === 'contract') {
// Check if current window is smaller
const windowLen = right - left;
if (windowLen < minLen) {
minLen = windowLen;
minStart = left;
document.getElementById('statusMessage').textContent =
`Valid window found! "${s.substring(left, right)}" (length ${windowLen}) - NEW MINIMUM!`;
} else {
document.getElementById('statusMessage').textContent =
`Valid window "${s.substring(left, right)}" (length ${windowLen}), but not smaller than best.`;
}
// Shrink from left
const leftChar = s[left];
window_counts[leftChar]--;
if (leftChar in required && window_counts[leftChar] < required[leftChar]) {
formed--;
phase = 'expand';
}
left++;
}
renderString();
renderRequired();
renderWindow();
updateVariables();
updateBestWindow();
}
function autoRun() {
if (isRunning) return;
isRunning = true;
const interval = setInterval(() => {
if (done) {
clearInterval(interval);
isRunning = false;
return;
}
step();
}, 500);
}
function reset() {
window_counts = {};
left = 0;
right = 0;
formed = 0;
minLen = Infinity;
minStart = 0;
done = false;
isRunning = false;
phase = 'expand';
document.getElementById('statusMessage').textContent =
`Find minimum window in "${s}" containing "${t}"`;
renderString();
renderRequired();
renderWindow();
updateVariables();
updateBestWindow();
}
reset();
</script>
</body>
</html>