Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
Example 1:
Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4. There may exists other ways to achieve this answer too.
Constraints:
1 <= s.length <= 105s consists of only uppercase English letters.0 <= k <= s.lengthProblem summary: You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Sliding Window
"ABAB" 2
"AABABBA" 1
longest-substring-with-at-most-k-distinct-characters)max-consecutive-ones-iii)minimum-number-of-operations-to-make-array-continuous)maximize-the-confusion-of-an-exam)longest-substring-of-one-repeating-character)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #424: Longest Repeating Character Replacement
class Solution {
public int characterReplacement(String s, int k) {
int[] cnt = new int[26];
int l = 0, mx = 0;
int n = s.length();
for (int r = 0; r < n; ++r) {
mx = Math.max(mx, ++cnt[s.charAt(r) - 'A']);
if (r - l + 1 - mx > k) {
--cnt[s.charAt(l++) - 'A'];
}
}
return n - l;
}
}
// Accepted solution for LeetCode #424: Longest Repeating Character Replacement
func characterReplacement(s string, k int) int {
cnt := [26]int{}
l, mx := 0, 0
for r, c := range s {
cnt[c-'A']++
mx = max(mx, cnt[c-'A'])
if r-l+1-mx > k {
cnt[s[l]-'A']--
l++
}
}
return len(s) - l
}
# Accepted solution for LeetCode #424: Longest Repeating Character Replacement
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
cnt = Counter()
l = mx = 0
for r, c in enumerate(s):
cnt[c] += 1
mx = max(mx, cnt[c])
if r - l + 1 - mx > k:
cnt[s[l]] -= 1
l += 1
return len(s) - l
// Accepted solution for LeetCode #424: Longest Repeating Character Replacement
use std::collections::HashMap;
impl Solution {
pub fn character_replacement(s: String, k: i32) -> i32 {
let s: Vec<char> = s.chars().collect();
let (mut res, mut l, mut maxf) = (0, 0, 0);
let mut count: HashMap<char, u64> = HashMap::new();
for r in 0..s.len() {
*count.entry(s[r]).or_default() += 1;
maxf = maxf.max(*count.get(&s[r]).unwrap());
while (r - l + 1) - maxf as usize > k as usize {
*count.get_mut(&s[l]).unwrap() -= 1;
l += 1;
}
res = res.max(r - l + 1);
}
res as i32
}
}
// Accepted solution for LeetCode #424: Longest Repeating Character Replacement
function characterReplacement(s: string, k: number): number {
const idx = (c: string) => c.charCodeAt(0) - 65;
const cnt: number[] = Array(26).fill(0);
const n = s.length;
let [l, mx] = [0, 0];
for (let r = 0; r < n; ++r) {
mx = Math.max(mx, ++cnt[idx(s[r])]);
if (r - l + 1 - mx > k) {
--cnt[idx(s[l++])];
}
}
return n - l;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.