-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest-repeating-character-replacement.ts
More file actions
43 lines (39 loc) · 1.37 KB
/
Copy pathlongest-repeating-character-replacement.ts
File metadata and controls
43 lines (39 loc) · 1.37 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
/**
* 424. Longest Repeating Character Replacement (Medium)
* Link: https://leetcode.com/problems/longest-repeating-character-replacement/
*
* Given a string `s` of uppercase letters and an integer `k`, you may replace at
* most k characters. Return the length of the longest substring containing a
* single repeated letter achievable after those replacements.
*
* Example:
* Input: s = "AABABBA", k = 1
* Output: 4 // replace one char to get "AABA" or "ABBB..." etc.
*
* Approach:
* Sliding window tracking letter counts and the count of the most frequent
* letter in the window (`maxFreq`). A window is valid when
* windowSize - maxFreq <= k (chars to replace). When it becomes invalid, slide
* the left edge. The answer is the largest window seen.
*
* Time: O(n)
* Space: O(1) — at most 26 counts.
*/
export function characterReplacement(s: string, k: number): number {
const counts = new Map<string, number>();
let left = 0;
let maxFreq = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
const ch = s[right];
counts.set(ch, (counts.get(ch) ?? 0) + 1);
maxFreq = Math.max(maxFreq, counts.get(ch)!);
while (right - left + 1 - maxFreq > k) {
const leftCh = s[left];
counts.set(leftCh, counts.get(leftCh)! - 1);
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}