k
characters.longest
to 0 to track the longest valid substring and left pointer l
to 0.counts
of size 26 to track the frequency of each uppercase letter.r
from 0 to the length of s
.s[r]
in counts using its ASCII value (i.e. ord(s[r]) - 65
).r - l + 1
) minus the maximum frequency in counts
exceeds k
, decrement the count of s[l]
and increment l
to shrink the window.longest
to the maximum of longest
and the current window size (i.e. r - l + 1
).longest
after the loop.class Solution:
def characterReplacement(self, s: str, k: int) -> int:
longest = 0
l = 0
counts = [0] * 26
for r in range(len(s)):
counts[ord(s[r]) - 65] += 1
while (r - l + 1) - max(counts) > k:
counts[ord(s[l]) - 65] -= 1
l += 1
longest = max(longest, (r - l + 1))
return longest
# Time Complexity: O(n)
# Space Complexity: O(1)
The goal of this problem is to find the longest substring where we can make all characters the same by replacing no more than k characters. The most effective approach for this type of problem is the sliding window technique.
The core idea is to maintain a "window" (a substring from a left
to a right
pointer) and a frequency count of the characters within that window. We expand this window by moving the right
pointer and check if the current window is "valid".
A window is considered valid if the number of characters we would need to replace to make it a single-character string is less than or equal to k
. This can be expressed with a simple formula: window_length - count_of_most_frequent_character <= k
. If the window becomes invalid, we shrink it by moving the left
pointer to the right, ensuring the condition is met again. We keep track of the maximum valid window size we have seen so far.
For example, given the string "AABABBA"
and k = 1
, the longest substring with repeating characters produced by replacing at most k
characters would be "[AABA]BBA"
or "AA[BABB]A"
. Hence, the output should be 4.
This is a foundational problem in the category of sliding window techniques. It's widely used in software interviews to assess a candidate's ability to manipulate pointers and use auxiliary data structures to solve real-time string-processing tasks efficiently.
The sliding window technique ensures that each character is added to and removed from the sliding window at most once. This results in a time complexity of O(n), where n is the length of the string. The space complexity is O(1), since the length of counts
is always 26, which does not change as the length of the input string s
changes.
The “Longest Repeating Character Replacement” problem is an elegant demonstration of how sliding window techniques can be used to reduce time complexity from exponential to linear. By keeping track of the characters dynamically and efficiently adjusting the window, we achieve both clarity and performance. This makes the solution highly scalable and applicable to real-time input processing such as streaming text or log data.