Longest Repeating Character Replacement LeetCode solution in JavaScript

1
// O(n) time | O(26) -> O(1) space - only uppercase English letters
2
var characterReplacement = function (s, k) {
3
const sLen = s.length,
4
charCount = {};
5
if (k >= sLen) return sLen;
6
let maxLen = 0,
7
windowStart = 0,
8
maxRepeatChar = 0;
9
for (let windowEnd = 0; windowEnd < sLen; windowEnd++) {
10
// increment charCount
11
charCount[s[windowEnd]]
12
? charCount[s[windowEnd]]++
13
: (charCount[s[windowEnd]] = 1);
14
// calc max repeating char
15
maxRepeatChar = Math.max(maxRepeatChar, charCount[s[windowEnd]]);
16
// calc number of char that is not (or has fewer chars) repeating in window
17
const remainingChar = windowEnd - windowStart + 1 - maxRepeatChar;
18
// slide window by incrementing start of window
19
if (remainingChar > k) {
20
// decrement charCount
21
charCount[s[windowStart]]--;
22
windowStart++;
23
}
24
// calc maxLen
25
maxLen = Math.max(maxLen, windowEnd - windowStart + 1);
26
}
27
return maxLen;
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0