Skip to content

Commit 7afd7ff

Browse files
committed
Add longest-repeating-character-replacement solution
1 parent e93aaf1 commit 7afd7ff

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
7+
// sliding window technique
8+
// Time complexity: O(n), where n is the length of the string. Both the start and end pointers traverse the string at most once.
9+
// Space Complexity: O(1), as we only need a fixed amount of extra space for the character frequency map and some variables.
10+
var characterReplacement = function (s, k) {
11+
let longest = 0;
12+
let maxCount = 0;
13+
const charCount = {};
14+
let start = 0;
15+
16+
for (let end = 0; end < s.length; end++) {
17+
const char = s[end];
18+
charCount[char] = (charCount[char] || 0) + 1;
19+
maxCount = Math.max(charCount[char], maxCount);
20+
21+
while (end - start + 1 - maxCount > k) {
22+
const temp = s[start];
23+
charCount[temp] -= 1;
24+
start += 1;
25+
}
26+
27+
longest = Math.max(longest, end - start + 1);
28+
}
29+
30+
return longest;
31+
};
32+

0 commit comments

Comments
 (0)