Skip to content

Commit 4b08997

Browse files
Jeehay28Jeehay28
authored andcommitted
Add longest-repeating-character-replacement solution in TS
1 parent 0fa4bbc commit 4b08997

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// TC: O(n)
2+
// SC: O(1)
3+
function characterReplacement(s: string, k: number): number {
4+
const freqMap = new Map<string, number>();
5+
let left = 0;
6+
let maxFreqCnt = 0;
7+
let result = 0;
8+
9+
for (let right = 0; right < s.length; right++) {
10+
const ch = s[right];
11+
freqMap.set(ch, (freqMap.get(ch)! | 0) + 1);
12+
maxFreqCnt = Math.max(maxFreqCnt, freqMap.get(ch)!);
13+
14+
while (right - left + 1 - maxFreqCnt > k) {
15+
// Shrink the sliding window by moving the left pointer to the right.
16+
// As we move left, decrease the frequency count of the character being excluded from the window.
17+
const ch = s[left];
18+
freqMap.set(ch, freqMap.get(ch)! - 1);
19+
left++;
20+
}
21+
22+
result = Math.max(result, right - left + 1);
23+
}
24+
25+
return result;
26+
}
27+

0 commit comments

Comments
 (0)