Skip to main content
Back to problems
#424
Medium Algorithms

Longest repeating character replacement

Hash Table String Sliding Window
59.1% acceptance
Jan 13, 2026
12889
759
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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn character_replacement(s: String, k: i32) -> i32 {
    let s: Vec<char> = s.chars().collect();
    let mut counts = [0; 26];
    let mut left = 0;
    let mut max_count = 0;
    let mut result = 0;
    
    for right in 0..s.len() {
      let idx = (s[right] as u8 - b'A') as usize;
      counts[idx] += 1;
      max_count = max_count.max(counts[idx]);
      
      while (right - left + 1) as i32 - max_count > k {
        let idx = (s[left] as u8 - b'A') as usize;
        counts[idx] -= 1;
        left += 1;
      }
      
      result = result.max(right - left + 1);
    }
    
    result as i32
  }
}