424. Longest Repeating Character Replacement
Description
Notes
Solution
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
char_freq = defaultdict(int)
# sliding window pointers
left, right = 0, 0
# answer
max_substring = 0
# could also be a for loop
while right < len(s):
char_freq[s[right]] += 1
# add 1 because a single letter would have a substring length of 1
width = right - left + 1
# The highest frequency letter will not be changed, as it will form the longest substring. So, its frequency
# is subtracted from the width of the sliding window. k is the number of letters to change. If the width
# minus the max frequency is greater than k, then the left side of the window needs to increment (and we
# need to decrement the letter that is leaving the sliding window).
if width - max(char_freq.values()) > k:
# if we're over k then we need to move the left side of the window along. But first decrement the
# character frequency as that instance of the letter is no longer part of the sliding window
char_freq[s[left]] -= 1
left += 1
else:
max_substring = max(max_substring, width)
right += 1
return max_substring
Last updated