1. Understand the Goal: The user wants a program that implements the "Longest Repeating Character Replacement" algorithm.
-
Identify the Problem:
- Input: A string
s (uppercase English letters only, usually) and an integer k.
- Operation: You can choose any character in the string and change it to any other uppercase English letter. You can perform this operation at most
k times.
- Output: The length of the longest substring containing the same letter after performing the above operations.
-
Determine the Approach:
- Brute Force: Check every substring, count frequencies, see if
length - max_freq <= k. This is O(n2) or worse. Not efficient for long strings.
- Sliding Window (Two Pointers): This is the standard optimal approach.
- Maintain a window
[left, right].
- Keep track of the frequency of characters within the current window.
- Keep track of
max_freq (the count of the most frequent character in the current window).
- Condition:
window_size - max_freq <= k.
- If the condition holds, the window is valid. We can try to expand it (move
right).
- If the condition fails, the window is invalid. We need to shrink it (move
left).
- Update the maximum length found so far.
-
Refine the Algorithm (Optimization Detail):
- There's a slight nuance in the sliding window implementation.
- Strict Sliding Window: When the window becomes invalid (
window_size - max_freq > k), increment left and decrement the count of s[left]. Then update max_freq. This is correct but updating max_freq can be tricky if you just decrement counts.
- Optimized/Lazy Sliding Window: We don't necessarily need to decrement
max_freq accurately. The max_freq might be higher than the actual max frequency in the current window, but that doesn't matter because we only care about the maximum length found. A higher max_freq simply means we allow the window to stay potentially larger or grow. Wait, actually, standard logic works fine.
- Let's stick to the standard logic:
count array/map of size 26.
max_count = 0
max_length = 0
left = 0
- Loop
right from 0 to n-1:
- Increment
count[s[right]].
max_count = max(max_count, count[s[right]]).
- If
(right - left + 1) - max_count > k:
- Decrement
count[s[left]].
- Increment
left.
max_length = max(max_length, right - left + 1).
-
Select Language: Python is generally the most readable for algorithmic interviews/examples. I will provide the solution in Python, but maybe C++ or Java as well? The prompt asks for "a program", implying one is sufficient, but providing Python is safe. I'll stick to Python for clarity, perhaps mention it's easily adaptable.
-
Drafting the Code (Python):
def characterReplacement(s: str, k: int) -> int:
count = {} # Map to store frequency of characters in current window
max_length = 0
left = 0
max_freq = 0
for right in range(len(s)):
# Add current char to window
count[s[right]] = count.get(s[right], 0) + 1
# Update the maximum frequency of any character seen so far in this window
max_freq = max(max_freq, count[s[right]])
# Check if the window is valid
# Window size is (right - left + 1)
# If (window size - max_frequency) > k, it means we need to change more than k chars
if (right - left + 1) - max_freq > k:
# Shrink window from left
count[s[left]] -= 1
left += 1
# Update result
max_length = max(max_length, right - left + 1)
return max_length
-
Edge Cases:
- Empty string? Loop won't run, returns 0. Correct.
k = 0? Standard sliding window. Correct.
k >= string length? The math (len - len) <= k holds, max_freq updates, window grows to full size. Correct.
-
Structuring the Output:
- State the problem clearly (LeetCode 424).
- Explain the logic (Sliding Window).
- Provide the code.
- Provide an example run to explain why it works.
- Mention Time and Space Complexity.
-
Refining the explanation of the Logic:
- The key insight is that we don't need to know which character is the majority one, just that there is one.
- Formula:
(window length) - (count of most frequent char) = (number of changes needed).
- If
(number of changes needed) <= k, we are good.
-
Final Code Check:
- Is
max_freq calculation robust? Yes. Note: technically, max_freq in the optimized version doesn't strictly decrease when the window shrinks, but since we only care about the max possible length, a historically higher max_freq doesn't hurt the validity (it just might keep the window slightly larger than necessary for a moment, but valid ones are the only ones extending max_length). However, to be strictly correct for the current window logic, simply doing max_freq = max(max_freq, current_char_count) is the standard O(N) solution.
- Wait, let's double check the
max_freq behavior.
- Example:
AABABBA, k=1.
- Window:
AABAB. max_freq (for A) = 3. Length 5. 5 - 3 <= 1. Valid.
- Next char:
B. Window AABABB. max_freq (for B) becomes 3? No, A is 3, B becomes 3. max_freq is 3. Length 6. 6 - 3 > 1. Invalid.
- Shrink:
left moves. A count drops to 2. left at index 1.
- Does
max_freq drop? In my code, no. It stays 3.
- Is this a problem?
- If
max_freq stays 3 but actual max is 2: . Since actual max is 2, is smaller (easier to satisfy ). So if fails, definitely fails. So it's safe. The window continues to shrink until valid.
This solution uses the Sliding Window technique to achieve O(N) time complexity, where N is the length of the string.
Python Implementation
def characterReplacement(s: str, k: int) -> int:
"""
Finds the length of the longest substring containing the same letter
after performing at most k operations.
"""
# Frequency map to count characters in the current window
count = {}
# Result (max length found so far)
res = 0
# Left pointer of the sliding window
left = 0
# Variable to track the frequency of the most frequent character
# in the current window
max_freq = 0
for right in range(len(s)):
# Add the current character to the window
count[s[right]] = count.get(s[right], 0) + 1
# Update max_freq.
# Note: We only need to check the frequency of the char we just added.
max_freq = max(max_freq, count[s[right]])
# Check if the current window is valid.
# The window is valid if: (Window Length - Count of Most Frequent Char) <= k
# If it's not valid, we need to shrink the window from the left.
while (right - left + 1) - max_freq > k:
# Remove the leftmost character from the counts
count[s[left]] -= 1
# Move the left pointer forward
left += 1
# Update the result if the current window is larger
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} -> Result: {characterReplacement(s1, k1)}")
# Expected: 4 (Replace both A's with B's or vice versa)
# Example 2
s2 = "AABABBA"
k2 = 1
print(f"String: {s2}, k: {k2} -> Result: {characterReplacement(s2, k2)}")
# Expected: 4 (Replace the middle A with B to get "AABBBBA" -> "BBBB")
Explanation of the Logic
- The Goal: We want a window of characters where the number of characters that are not the majority character is less than or equal to
k.
- Mathematically:
Window Length - (Count of Most Frequent Char) <= k
- Sliding Window: We expand the window by moving the
right pointer.
- Frequency Count: We maintain a hash map (
count) to track how many times each character appears in the current window. We also track max_freq, which is the count of the most frequent character seen in the current window.
- Shrinking the Window: If the condition
(window_len - max_freq) > k is met, it means we have made too many changes to make the string uniform. We must shrink the window from the left side until it becomes valid again.
- Optimization: We do not need to recalculate
max_freq from scratch when we shrink the window. Even if max_freq is slightly outdated (larger than the actual max in the current window), it doesn't hurt the logic; it just makes our condition slightly stricter, resulting in a valid window.
Complexity Analysis
- Time Complexity: O(N). We iterate through the string with the
right pointer once. The left pointer also only moves forward. The while loop runs a total of N times across the entire execution, not per iteration of the for loop.
- Space Complexity: O(1). Since the input string consists of uppercase English letters, the
count hash map will store at most 26 keys.