-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0424_longest_repeating_character.html
More file actions
393 lines (340 loc) · 15.3 KB
/
0424_longest_repeating_character.html
File metadata and controls
393 lines (340 loc) · 15.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Longest Repeating Character Replacement - LeetCode 424</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">#424</span> Longest Repeating Character Replacement</h1>
<p>Given a string and k replacements allowed, find the longest substring with all same characters. The trick: keep track of the most frequent character in the window!</p>
<div class="problem-meta">
<span class="meta-tag">🪟 Sliding Window</span>
<span class="meta-tag">🔤 String</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <a href="../python/0424_longest_repeating_character_replacement/0424_longest_repeating_character_replacement.py">0424_longest_repeating_character_replacement.py</a>
</div>
</div>
<div class="explanation-panel">
<h4>💡 How It Works (Layman's Terms)</h4>
<ul>
<li><strong>Goal:</strong> Find the longest substring where all characters are the same, using at most k replacements</li>
<li><strong>Key insight:</strong> In any valid window, we keep the most frequent character and replace the others</li>
<li><strong>Formula:</strong> replacements_needed = window_size - max_frequency</li>
<li><strong>Valid window:</strong> When replacements_needed ≤ k</li>
<li><strong>Expand:</strong> Move right pointer, add character to window</li>
<li><strong>Shrink:</strong> When we need more than k replacements, move left pointer</li>
<li><strong>Track max:</strong> Keep track of the maximum valid window size we've seen</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">
k = 2 (can replace up to 2 characters)
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to find the longest substring with replacements
</div>
<div class="variable-display">
<div class="variable-box">
<div class="variable-name">Window Size</div>
<div class="variable-value" id="windowVal">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Max Frequency</div>
<div class="variable-value" id="freqVal">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Replacements Needed</div>
<div class="variable-value" id="replaceVal">0</div>
</div>
<div class="variable-box">
<div class="variable-name">Max Length</div>
<div class="variable-value" id="maxVal">0</div>
</div>
</div>
<div class="array-section">
<div class="array-label">String:</div>
<div class="array-container" id="stringContainer"></div>
</div>
<div class="array-section">
<div class="array-label">Character Counts in Window:</div>
<div id="countsContainer" style="display: flex; gap: 10px; flex-wrap: wrap;"></div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from collections import defaultdict
"""
LeetCode Longest Repeating Character Replacement
Problem from LeetCode: https://leetcode.com/problems/longest-repeating-character-replacement/
You are given a string s and an integer k. You can choose any character of the string and
change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after
performing the above operations.
Example 1:
Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input: s = "AABABBA", k = 1
Output: 4
Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
Constraints:
1 <= s.length <= 10^5
s consists of only uppercase English letters.
0 <= k <= s.length
"""
class Solution:
def character_replacement(self, s: str, k: int) ->int:
"""
Find the length of the longest substring containing the same letter after
replacing at most k characters.
Args:
s: The input string
k: The maximum number of characters to replace
Returns:
int: Length of the longest substring with same letter after replacements
"""
occurrence = [0] * 26
left = 0
max_occurrence = 0
max_length = 0
for right in range(len(s)):
char_index = ord(s[right]) - ord('A')
occurrence[char_index] += 1
max_occurrence = max(max_occurrence, occurrence[char_index])
if right - left + 1 - max_occurrence > k:
occurrence[ord(s[left]) - ord('A')] -= 1
left += 1
max_length = max(max_length, right - left + 1)
return max_length
def characterReplacement_dict(self, s: str, k: int) ->int:
"""
Implementation using a defaultdict for character counting.
Args:
s: The input string
k: The maximum number of characters to replace
Returns:
int: Length of the longest substring with same letter after replacements
"""
char_counts = defaultdict(int)
left = 0
max_occurrence = 0
max_length = 0
for right in range(len(s)):
char_counts[s[right]] += 1
max_occurrence = max(max_occurrence, char_counts[s[right]])
if right - left + 1 - max_occurrence > k:
char_counts[s[left]] -= 1
left += 1
max_length = max(max_length, right - left + 1)
return max_length
def characterReplacement_optimized(self, s: str, k: int) ->int:
"""
Optimized implementation that avoids recalculating max each time.
Args:
s: The input string
k: The maximum number of characters to replace
Returns:
int: Length of the longest substring with same letter after replacements
"""
char_counts = defaultdict(int)
left = 0
max_occurrence = 0
for right in range(len(s)):
char_counts[s[right]] += 1
max_occurrence = max(max_occurrence, char_counts[s[right]])
window_size = right - left + 1
if window_size - max_occurrence > k:
char_counts[s[left]] -= 1
left += 1
return len(s) - left
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1: s = "ABAB", k = 2
print("Example 1:")
result = solution.character_replacement("ABAB", 2)
print(f"Output: {result}") # Expected: 4
# Example 2: s = "AABABBA", k = 1
print("\nExample 2:")
result = solution.character_replacement("AABABBA", 1)
print(f"Output: {result}") # Expected: 4
# Test with alternative implementations
print("\nAlternative implementations:")
print("Dict approach:", solution.characterReplacement_dict("ABAB", 2))
print("Optimized approach:", solution.characterReplacement_optimized("ABAB", 2))
</pre>
</div>
</div>
</div>
<script>
const s = "AABABBA";
const k = 2;
let charCounts = {};
let left = 0;
let right = -1;
let maxFreq = 0;
let maxLength = 0;
let phase = 'init';
let autoInterval = null;
function init() {
renderString();
renderCounts();
document.getElementById('windowVal').textContent = '0';
document.getElementById('freqVal').textContent = '0';
document.getElementById('replaceVal').textContent = '0';
document.getElementById('maxVal').textContent = '0';
}
function renderString() {
const container = document.getElementById('stringContainer');
container.innerHTML = '';
s.split('').forEach((char, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `char-${idx}`;
box.style.width = '50px';
box.innerHTML = `${char}<span class="index-label">[${idx}]</span>`;
if (idx >= left && idx <= right) {
box.classList.add('current');
}
if (idx === right) {
box.classList.add('highlight');
}
container.appendChild(box);
});
// Draw window indicators
if (right >= 0) {
let windowIndicator = document.getElementById('windowIndicator');
if (!windowIndicator) {
windowIndicator = document.createElement('div');
windowIndicator.id = 'windowIndicator';
windowIndicator.style.cssText = 'margin-top: 10px; display: flex; gap: 8px;';
container.parentNode.appendChild(windowIndicator);
}
let html = '';
for (let i = 0; i < s.length; i++) {
html += '<div style="width: 50px; text-align: center; font-size: 0.9em;">';
if (i === left) html += '<span style="color: #ff5722; font-weight: bold;">L↑</span>';
else if (i === right) html += '<span style="color: #3f51b5; font-weight: bold;">R↑</span>';
html += '</div>';
}
windowIndicator.innerHTML = html;
}
}
function renderCounts() {
const container = document.getElementById('countsContainer');
container.innerHTML = '';
if (Object.keys(charCounts).length === 0) {
container.innerHTML = '<span style="color: #999;">No characters in window yet</span>';
return;
}
Object.entries(charCounts).sort().forEach(([char, count]) => {
if (count > 0) {
const box = document.createElement('div');
box.className = 'variable-box';
box.innerHTML = `<div class="variable-name">${char}</div><div class="variable-value">${count}
</div>`;
if (count === maxFreq) {
box.style.borderColor = '#4caf50';
box.style.background = '#e8f5e9';
}
container.appendChild(box);
}
});
}
function step() {
if (phase === 'init') {
phase = 'expanding';
right = -1;
document.getElementById('statusMessage').textContent =
'Starting sliding window. Expand right pointer to find valid windows.';
}
if (phase === 'expanding') {
right++;
if (right >= s.length) {
phase = 'done';
document.getElementById('statusMessage').textContent =
`✅ Done! Maximum length with ${k} replacements: ${maxLength}`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
// Add character
charCounts[s[right]] = (charCounts[s[right]] || 0) + 1;
maxFreq = Math.max(maxFreq, charCounts[s[right]]);
const windowSize = right - left + 1;
const replacementsNeeded = windowSize - maxFreq;
document.getElementById('windowVal').textContent = windowSize;
document.getElementById('freqVal').textContent = maxFreq;
document.getElementById('replaceVal').textContent = replacementsNeeded;
if (replacementsNeeded > k) {
// Need to shrink
document.getElementById('statusMessage').textContent =
`Window [${left},${right}]: "${s.substring(left, right + 1)}" needs ${replacementsNeeded} replacements > k=${k}. Shrinking!`;
charCounts[s[left]]--;
left++;
} else {
maxLength = Math.max(maxLength, windowSize);
document.getElementById('maxVal').textContent = maxLength;
document.getElementById('statusMessage').textContent =
`Window [${left},${right}]: "${s.substring(left, right + 1)}" size=${windowSize}, most freq=${maxFreq}, replacements=${replacementsNeeded} ≤ k=${k}. Valid! Max=${maxLength}`;
}
renderString();
renderCounts();
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (phase === 'done') {
stopAuto();
} else {
step();
}
}, 1300);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
phase = 'init';
left = 0;
right = -1;
charCounts = {};
maxFreq = 0;
maxLength = 0;
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').textContent =
'Click "Step" or "Auto Run" to find the longest substring with replacements';
const windowIndicator = document.getElementById('windowIndicator');
if (windowIndicator) windowIndicator.remove();
init();
}
init();
</script>
</body>
</html>