BackendML

Longest Repeating Character Replacement

Medium2 min read
The Longest Repeating Character Replacement problem requires finding the longest substring that can be transformed into a string containing only the same character by replacing at most k characters.

Problem

You are given a string s and an integer k. You can replace at most k characters in the string with any uppercase English letter.

Return the length of the longest substring that can be transformed into a string containing only the same character after performing at most k replacements.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

s = "AABABBA" 
k = 1 

Output

4 

Solution

This solution uses the Sliding Window technique along with a frequency array to keep track of how many times each character appears in the current window.

As the window expands, the frequency of the newly added character is updated, and the frequency of the most common character in the current window is maintained.

The number of characters that need to be replaced is calculated as windowSize - maxFrequency. This works because all other characters in the window must be changed to match the most frequent character.

If the number of required replacements becomes greater than k, the window is no longer valid. The left side of the window is then moved forward, reducing the frequency of the character that leaves the window, until the window becomes valid again.

Throughout the traversal, we keep track of the largest valid window. Its size is the length of the longest substring that can be formed after replacing at most k characters.
class Solution {
    public int characterReplacement(String s, int k) {
        int left = 0;
        int max = 0;
        int maxFrequency = 0;

        int[] freq = new int[26];

        for (int right = 0; right < s.length(); right++) {
            freq[s.charAt(right) - 'A']++;

            maxFrequency = Math.max(
                maxFrequency,
                freq[s.charAt(right) - 'A']
            );

            if ((right - left + 1) - maxFrequency > k) {
                freq[s.charAt(left) - 'A']--;
                left++;
            }

            max = Math.max(max, right - left + 1);
        }

        return max;
    }
}

Complexity

The algorithm scans the string only once using a sliding window. Each character is added to and removed from the window at most once, resulting in an overall time complexity of O(n).

The frequency array has a fixed size of 26, so the extra space complexity is O(1).

Comments

No comments yet. Ask a question or share what helped.