|
| 1 | +/** |
| 2 | + * @param {string} str |
| 3 | + * @param {number} maxConvertCount |
| 4 | + * @return {number} |
| 5 | + */ |
| 6 | +var characterReplacement = function (str, maxConvertCount) { |
| 7 | + const freqInWindow = {}; |
| 8 | + let maxLength = 0; |
| 9 | + let maxCharFreqInWindow = 0; |
| 10 | + let leftIndex = 0; |
| 11 | + |
| 12 | + for (let rightIndex = 0; rightIndex < str.length; rightIndex++) { |
| 13 | + const slidingWindow = [str[leftIndex], str[rightIndex]]; |
| 14 | + const [leftChar, rightChar] = slidingWindow; |
| 15 | + |
| 16 | + freqInWindow[rightChar] = (freqInWindow[rightChar] || 0) + 1; |
| 17 | + maxCharFreqInWindow = Math.max( |
| 18 | + maxCharFreqInWindow, |
| 19 | + freqInWindow[rightChar] |
| 20 | + ); |
| 21 | + |
| 22 | + // while (currentWindowLength > maxConvertCount + maxCharFreqInWindow) { |
| 23 | + // while (cannot convert all characters in the window to the same character) { |
| 24 | + while (rightIndex - leftIndex + 1 > maxConvertCount + maxCharFreqInWindow) { |
| 25 | + leftIndex += 1; |
| 26 | + freqInWindow[leftChar] -= 1; |
| 27 | + } |
| 28 | + |
| 29 | + maxLength = Math.max(maxLength, rightIndex - leftIndex + 1); |
| 30 | + } |
| 31 | + |
| 32 | + return maxLength; |
| 33 | +}; |
| 34 | + |
| 35 | +/** |
| 36 | + * Time Complexity: O(n) |
| 37 | + * - The right pointer iterates through the string once, making it O(n). |
| 38 | + * - The left pointer only moves when necessary, also contributing to O(n) overall. |
| 39 | + * - Thus, the total time complexity is O(n). |
| 40 | + * |
| 41 | + * Space Complexity: O(1) |
| 42 | + * - The frequency object stores counts for at most 26 letters in the English alphabet. |
| 43 | + * - Since the space used by the frequency object is constant and does not scale with input size, |
| 44 | + * the space complexity is O(1). |
| 45 | + */ |
0 commit comments