This visualization was generated with AI assistance. View problem on LeetCode
Home Algorithms Longest Repeating Character Replacement

Longest Repeating Character Replacement

An interactive visualization of the sliding window algorithm that finds the longest substring with same characters after at most k replacements.

Sliding Window LC 424 Medium

Problem Statement

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.

Interactive Visualization

Presets:
Window Size
0
Max Frequency
0
Replacements Needed
0
k (Max Allowed)
0
Max Length
0
Character Frequency in Window
Start the algorithm to see frequency data
Click Step or Play to start
Code
fun characterReplacement(s: String, k: Int): Int {    val count = mutableMapOf<Char, Int>()    var left = 0    var maxFreq = 0    var maxLen = 0    for (right in s.indices) {        count[s[right]] = (count[s[right]] ?: 0) + 1        maxFreq = maxOf(maxFreq, count[s[right]]!!)        while ((right - left + 1) - maxFreq > k) {            count[s[left]] = count[s[left]]!! - 1            left++        }        maxLen = maxOf(maxLen, right - left + 1)    }    return maxLen}

Key Insight

The sliding window technique maintains a window where the number of characters that need to be replaced (window size minus the most frequent character count) is at most k. By tracking the maximum frequency in the current window, we can efficiently determine when to shrink the window from the left.

Algorithm Steps

  1. Initialize a frequency map, two pointers (left and right), max_freq, and max_len
  2. Expand the window by moving right pointer and update character frequency
  3. Update max_freq to track the highest frequency character in current window
  4. If (window_size - max_freq) > k, shrink window from left until condition is satisfied
  5. Update max_len with the current valid window size
  6. Repeat until right pointer reaches the end of string

Complexity Analysis

Time Complexity O(n) where n is the length of the string
Space Complexity O(1) - frequency map contains at most 26 uppercase letters