Taro Logo

Longest Repeating Character Replacement

#5 Most AskedMedium
Topics:
StringsSliding Windows

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 <= 105
  • s consists of only uppercase English letters.
  • 0 <= k <= s.length

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the character set of the input string `s`? Can we assume it consists exclusively of uppercase English letters as stated in the problem description?
  2. What is the maximum length of the string `s`, and what are the possible ranges for `k` relative to the length of `s` (e.g., can $k$ be larger than the length of $s$)?
  3. How should we handle edge cases where the string `s` is empty or has a length of 1?
  4. Could `k` be 0, meaning we cannot perform any character replacements at all?
  5. Is the input string guaranteed to be non-null, and should we expect any whitespace or special characters?

Brute Force Solution

Approach

The brute force approach to finding the longest repeating character replacement involves checking every possible piece of the text and seeing if we can make it all the same letter by swapping a limited number of characters. We simply test every single option exhaustively from start to finish to see which one gives us the longest stretch.

Here's how the algorithm would work step-by-step:

  1. Look at every possible starting point in the text.
  2. From each starting point, look at every possible ending point to form a section of text.
  3. For every section you look at, count how many times each letter appears and figure out which letter appears the most.
  4. Calculate how many letters you would need to change to make every single character in that section match that most frequent letter.
  5. Check if the number of changes you need is less than or equal to the allowed limit.
  6. If the changes are within the limit, measure the length of this section and remember it if it is the longest one you have found so far.
  7. Repeat this process for every possible section of the text until you have checked them all, and then report the largest length you recorded.

Code Implementation

def character_replacement(input_string, max_replacements):
    maximum_length = 0
    string_length = len(input_string)
    
    # Iterate through every possible starting point to evaluate all substrings
    for start_index in range(string_length):
        for end_index in range(start_index, string_length):
            current_window = input_string[start_index:end_index + 1]
            character_counts = {}
            highest_frequency = 0
            
            for character in current_window:
                character_counts[character] = character_counts.get(character, 0) + 1
                if character_counts[character] > highest_frequency:
                    highest_frequency = character_counts[character]
            
            window_length = end_index - start_index + 1
            characters_to_change = window_length - highest_frequency
            
            # Ensure the required replacements do not exceed the allowed limit
            if characters_to_change <= max_replacements:
                if window_length > maximum_length:
                    maximum_length = window_length
                    
    return maximum_length

Big(O) Analysis

Time Complexity
O(n³) – Given a string of length n, the first loop picks every possible starting point and the second nested loop picks every possible ending point, generating O(n²) distinct substrings. For each of these substrings, we spend O(n) time counting the character frequencies to determine the most frequent letter and required replacements. Multiplying the O(n²) substrings by the O(n) work per substring yields approximately n cubed over 6 operations, which simplifies to the final cubic time complexity.
Space Complexity
O(1) – The brute force approach examines every possible starting and ending point of the text without utilizing any dynamic auxiliary data structures that scale with the input size N. The space complexity is limited to a few primitive scalar variables used to track the starting points, ending points, letter counts, and the maximum length found so far. These few tracking variables require a constant amount of extra memory regardless of how long the input text is. Therefore, the total auxiliary space complexity simplifies to O(1).

Optimal Solution

Approach

Instead of checking every possible section of letters, we use a sliding window approach that expands as long as the rule is followed. When the rule is broken, the window simply slides forward instead of shrinking, ensuring we only ever track the longest valid section found.

Here's how the algorithm would work step-by-step:

  1. Imagine you are looking at a row of colored blocks through a sliding frame, where you are allowed to swap a limited number of blocks to make them all the same color.
  2. Start with a very small frame at the very beginning of the row and make the frame larger by moving its right edge forward step by step.
  3. As the frame grows, keep track of which color appears the most frequently inside the frame, and calculate how many other blocks would need to be changed to match that most frequent color.
  4. If the number of blocks that need to be changed is within your allowed limit, your current frame is valid, so measure its size and remember it as a potential record.
  5. If the number of blocks that need to be changed exceeds your allowed limit, it means your frame has become too messy.
  6. Instead of shrinking your frame, simply slide the entire frame forward while keeping its current size, because you are only interested in finding a section larger than any valid one you have already seen.
  7. Continue sliding forward until you reach the end of the row, and the largest valid frame size you recorded along the way will be your final answer.

Code Implementation

def character_replacement(input_string, allowed_replacements):
    character_counts = {}
    left_pointer = 0
    max_frequency = 0

    for right_pointer in range(len(input_string)):
        current_character = input_string[right_pointer]
        character_counts[current_character] = character_counts.get(current_character, 0) + 1
        max_frequency = max(max_frequency, character_counts[current_character])

        # We only slide the window instead of shrinking it because we only care about beating our longest valid length.
        if (right_pointer - left_pointer + 1) - max_frequency > allowed_replacements:
            
            left_character = input_string[left_pointer]
            character_counts[left_character] -= 1
            left_pointer += 1

    # The total window size remains at its maximum achieved length because we never shrink the sliding frame.
    return right_pointer - left_pointer + 1

Big(O) Analysis

Time Complexity
O(n) – As the right edge of the sliding window iterates once through all n characters of the string, the left edge only moves forward when the window becomes invalid. Because the window size never shrinks and only stays the same or grows when a new maximum is found, the left and right pointers each traverse the string at most once. Tracking the character frequencies takes constant time since the alphabet size is fixed at 26 uppercase English letters. This ensures the total operations scale linearly with n, simplifying the overall complexity to O(n).
Space Complexity
O(1) – To keep track of which color appears the most frequently inside the frame, the algorithm utilizes a fixed-size frequency map or array to store the counts of uppercase English letters. Because the alphabet is limited to a constant 26 characters, this auxiliary data structure occupies a fixed amount of memory regardless of the input string length N. In addition to the frequency array, only a few primitive integer variables are used to maintain the sliding window boundaries and the maximum frequency. Therefore, the auxiliary space complexity remains constant, as the extra memory required does not grow with the size of the input.

Edge Cases

Empty string input where s is empty
How to Handle:
The sliding window loop will not execute and naturally return zero as the longest length
String length is smaller than or equal to k
How to Handle:
The entire string can be converted to a single character so the length of the string is returned
String contains all identical characters
How to Handle:
The window expands to the full length of the string since no replacements are needed
K is equal to zero
How to Handle:
The algorithm finds the length of the longest existing contiguous block of identical characters without making any replacements
Maximum possible constraint values for string length up to 10 to the 5th power
How to Handle:
The two-pointer sliding window approach scales linearly with O of n time complexity to pass efficiently
Alternating characters with a small k value such as ababab and k equals one
How to Handle:
The window correctly slides and maintains a maximum valid length of three by replacing a single alternating character
Frequency count optimization where max frequency is not recomputed when the window shrinks
How to Handle:
Our solution relies on a historical max frequency which is sufficient because a smaller valid window size cannot be beaten anyway
0/9 completed