1. Understand the Goal: The user wants a program to solve the "Longest Repeating Character Replacement" problem. This is a classic algorithmic problem often found on platforms like LeetCode (Problem 424).
Problem Definition:
Input: A string s (uppercase English letters) and an integer k.
Operation: You can change any character in s to any other uppercase English letter at most k times.
Output: The length of the longest substring containing the same letter after performing at most k operations.
Algorithm Selection:
Brute Force: Check every substring, count the most frequent character, see if length - max_count <= k. This is O(N2) or worse, too slow for large inputs.
Sliding Window (Two Pointers): This is the standard optimal approach.
Maintain a window [left, right].
Expand the window by moving right.
Track the frequency of characters in the current window.
Track the count of the most frequent character in the current window (max_count).
The condition to check: (window_length) - (max_count) <= k.
If valid: Update max length.
If invalid: Shrink window from the left (left++).
Optimization Note: Strictly speaking, we don't need to decrement max_count when shrinking the window, because we only care about the maximum valid window length we've seen so far. Even if the window size stays larger than strictly valid, it doesn't affect the max_len variable because we already found a valid window of that size. However, for correctness in logic (though not strictly necessary for the final answer), some implementations reset or reduce the window size. The standard optimized approach keeps the window size non-decreasing (never shrinks, just shifts), making it O(N).
Wait, actually: The standard implementation usually shifts left when window_len - max_count > k.
Let's refine the O(N) approach:
max_count refers to the global max frequency seen so far in the entire string history, not necessarily the current window.
Why? Because if we found a window of size 10 where 'A' appeared 8 times, we are looking for a window of size 11. If the current window has a max count of 7, we know we can't make a window of size 11, so we just slide left and right by 1.
Condition: (right - left + 1) - max_frequency > k.
If true: left++ (shift window).
Update max_len.
Language Selection: Python is generally the most readable and widely understood for these types of algorithm requests, but I should probably provide a solution in Python and maybe C++ or Java for completeness. I'll stick to Python as the primary explanation and perhaps offer C++ as an alternative or just stick to Python for clarity unless asked otherwise. I'll provide Python.
Drafting the Code (Python):
python
def characterReplacement(s: str, k: int) -> int:
count = {} # Frequency map
res = 0 # Max length found
l = 0 # Left pointer
maxf = 0 # Max frequency of a single character in the current window
for r in range(len(s)):
count[s[r]] = 1 + count.get(s[r], 0)
maxf = max(maxf, count[s[r]])
# Check if current window is valid
# Window size is (r - l + 1)
# If (window size - most frequent char count) > k, it's invalid
while (r - l + 1) - maxf > k:
count[s[l]] -= 1
l += 1
res = max(res, r - l + 1)
return res
Self-Correction on the while loop: Technically, maxf never decreases in the simple logic above. This is a common point of confusion.
If maxf is the global max count encountered ever, then (r - l + 1) - maxf > k is the condition. If it fails, we increment l. The window size r - l + 1 never actually grows until we find a new higher frequency character.
This works because we only care about the maximum length. We don't need to strictly maintain a "valid" window at all times, just a window that could be valid if we had a higher frequency.
However, the standard readable version usually updates the maxf inside the loop.
Actually, recalculating max(count.values()) every iteration is O(26), which is constant time. Doing it inside the while loop is fine and easier to explain.
Let's stick to the O(N) logic without recalculating max:
Increment count[s[r]].
Update maxf = max(maxf, count[s[r]]).
While (r - l + 1) - maxf > k:
Decrement count[s[l]].
Increment l.
Update res.
Note: Even if maxf is technically slightly "wrong" for the current window (because we don't decrease it when l moves), the result is correct because res only updates when we have a valid scenario (or a potentially better one). The window size effectively never shrinks below res.
Simplification: Most people prefer the logic where the window size is strictly managed.
Let's write the most robust, standard version.
Language: I will provide the solution in Python and Java, as those are the most common languages for this type of interview question.
Structuring the Output:
Explain the problem briefly.
Explain the Sliding Window approach.
Provide the Python code.
Provide an example usage.
(Optional but good) Provide a Java version.
Explain the Time/Space complexity (O(N) time, O(1) space since alphabet size is fixed at 26).
def characterReplacement(s: str, k: int) -> int:
char_count = {}
max_count = 0
left = 0
max_length = 0
for right in range(len(s)):
char_count[s[right]] = char_count.get(s[right], 0) + 1
max_count = max(max_count, char_count[s[right]])
# If the window size minus the count of the most frequent char
# is greater than k, we need to shrink the window
while (right - left + 1) - max_count > k:
char_count[s[left]] -= 1
left += 1
max_length = max(max_length, right - left + 1)
return max_length
This solution uses the Sliding Window technique to achieve O(N) time complexity.
The Algorithm
We maintain a window defined by left and right pointers.
As we expand the window to the right, we count the frequency of each character.
We track max_frequency, the count of the most frequent character in the current window.
The key formula is determining if the current window is valid:
Window Size - max_frequency = Number of replacements needed.
If the replacements needed exceed k, the window is too big. We must shrink it from the left.
The result is the maximum window size we achieved during the process.
Python Implementation
python
def characterReplacement(s: str, k: int) -> int:
"""
Finds the length of the longest substring with the same letters
after performing at most k replacements.
"""
# Dictionary to keep track of the count of characters in the current window
count = {}
# Result variable to store the max length found so far
res = 0
# Left pointer of the sliding window
left = 0
# Variable to track the frequency of the most common character in the current window
max_frequency = 0
# Iterate over the string with the right pointer
for right in range(len(s)):
# Update the count of the current character
count[s[right]] = 1 + count.get(s[right], 0)
# Update the max_frequency seen in the current window
# (We only care if the new character increases the max frequency)
max_frequency = max(max_frequency, count[s[right]])
# Check if the current window is valid.
# Condition: (Window Length - Count of most frequent char) <= k
# If this is false, our replacements exceed the limit k.
while (right - left + 1) - max_frequency > k:
# The window is invalid, so we shrink it from the left
count[s[left]] -= 1
left += 1
# Note: We technically could recalculate max_frequency here by scanning
# the count dictionary (max(count.values())), but that would make
# the complexity O(26 * N) or O(N).
# Since max_frequency only determines the *historical* max valid window size,
# we don't need to decrement it for the logic to work.
# We only care if we find a NEW higher frequency later.
# Update the result with the current valid window size
res = max(res, right - left + 1)
return res
# --- Example Usage ---
if __name__ == "__main__":
# Example 1
s1 = "ABAB"
k1 = 2
print(f"String: {s1}, k: {k1}")
print(f"Longest Length: {characterReplacement(s1, k1)}") # Output: 4
# Example 2
s2 = "AABABBA"
k2 = 1
print(f"\nString: {s2}, k: {k2}")
print(f"Longest Length: {characterReplacement(s2, k2)}") # Output: 4
Complexity Analysis
Time Complexity: O(N)
We iterate through the string once with the right pointer.
The left pointer also only moves forward (it never backtracks).
Therefore, the total operations are linear relative to the length of the string.
Space Complexity: O(1)
We use a dictionary (or hash map) to store counts. Since the input consists of uppercase English letters, the map will hold at most 26 keys. Thus, the space used is constant.
Explanation of the "max_frequency" Optimization
You might notice that we do not decrease max_frequency when the left pointer moves.
Let's say we found a window of size 5 where the max frequency was 3.
If we shrink the window, the max_frequency variable might technically be "wrong" (e.g., it stays 3, but the actual max in the new smaller window is 2).
This is acceptable because we only care about finding the Longest window.
The variable res stores the maximum length found so far. We only update res when we find a window size larger than our current record.
To find a larger window, we naturally need a higher max_frequency.
Therefore, keeping the historical maximum allows the window to "slide" efficiently without recalculating the max on every step.
Java Implementation:
java
public int characterReplacement(String s, int k) {
int[] count = new int[26];
int maxCount = 0;
int left = 0;
int maxLength = 0;
for (int right = 0; right < s.length(); right++) {
count[s.charAt(right) - 'A']++;
maxCount = Math.max(maxCount, count[s.charAt(right) - 'A']);
while ((right - left + 1) - maxCount > k) {
count[s.charAt(left) - 'A']--;
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
Final Review:
Does the logic hold? Yes.
Is the explanation clear? I should explain whymaxCount doesn't need to decrease. (It doesn't invalidate the answer because we only care about finding a larger window, which requires a largermaxCount).
Time Complexity: O(N) since we pass the string once.
Space Complexity: O(1) (or O(26)) for the map.
Formatting: Use code blocks, bold text for emphasis, and clear steps.
Self-Correction during drafting response:
I should clarify the "maxCount doesn't decrease" trick. While correct for the length result, it makes the window size technically "incorrect" momentarily regarding validity (it might count a char that is no longer in the window towards maxCount). However, since the window size right - left + 1 is bound by maxLength (which is derived from the highest maxCount seen so far), the algorithm works. If a new max frequency appears, the window expands. If not, it slides. I will present the code that is easiest to understand, which is often the one that just handles the logic correctly, even if the optimization is subtle.
Actually, let's stick to the standard LeetCode solution pattern which is the one written above. It's O(N).
Let's construct the final response.
Here is a complete solution in Python implementing the Longest Repeating Character Replacement algorithm.