← Back to Codes

2026-06-09 16:36:42

Longest Repeating Character Replacement in Python and Java | LeetCode #424

Learn how to solve Longest Repeating Character Replacement in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Longest Repeating Character Replacement in Python and Java

In this tutorial, we will learn LeetCode #424: Longest Repeating Character Replacement in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Longest Repeating Character Replacement Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use sliding window because it gives a clean and optimized solution.

Example input:
s = "AABABBA", k = 1

Expected result:
Output: 4

Explanation:
AABA can become AAAA by replacing B.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
s = "AABABBA", k = 1

Approach:
sliding window

We update variables step by step until we reach:
Output: 4

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why sliding window is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

s = "AABABBA", k = 1

We will solve it using sliding window.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: 4

Why?
AABA can become AAAA by replacing B.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: 4

Example 1

Input:
s = "AABABBA", k = 1

Output:
Output: 4

Explanation:
AABA can become AAAA by replacing B.

Example 2

Input:
s = "AABABBA", k = 1

Output:
4

Explanation:
Replace one character to make a length 4 repeating substring.

Python Code

Here is the complete Python solution for LeetCode #424.

class CharacterReplacementFinder:
    def character_replacement(self, text, k):
        counts = {}
        left = 0
        max_count = 0
        best = 0

        for right, char in enumerate(text):
            counts[char] = counts.get(char, 0) + 1
            max_count = max(max_count, counts[char])

            while (right - left + 1) - max_count > k:
                counts[text[left]] -= 1
                left += 1

            best = max(best, right - left + 1)

        return best


finder = CharacterReplacementFinder()
print(finder.character_replacement("AABABBA", 1))  # Output: 4
print(finder.character_replacement("ABBBAC", 2))   # Output: 5

Java Code

Here is the complete Java solution for LeetCode #424.

class CharacterReplacementFinder {
    public int characterReplacement(String text, int k) {
        int[] counts = new int[26];
        int left = 0;
        int maxCount = 0;
        int best = 0;

        for (int right = 0; right < text.length(); right++) {
            int index = text.charAt(right) - 'A';
            counts[index]++;
            maxCount = Math.max(maxCount, counts[index]);

            while ((right - left + 1) - maxCount > k) {
                counts[text.charAt(left) - 'A']--;
                left++;
            }

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

        return best;
    }

    public static void main(String[] args) {
        CharacterReplacementFinder finder = new CharacterReplacementFinder();
        System.out.println(finder.characterReplacement("AABABBA", 1)); // 4
        System.out.println(finder.characterReplacement("ABBBAC", 2));  // 5
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #424: Longest Repeating Character Replacement becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.