Longest Repeating Character Replacement

Finding Longest Repeating Character Replacement Problem

You are given a string s that contains only uppercase English letters and an integer k. Your task is to determine the length of the longest substring in s that can consist of just one distinct character after modifying the string.

You are allowed to make up to k replacements, where each replacement involves changing any character in the substring to another uppercase English letter.

The goal is to maximize the length of this uniform substring by carefully choosing which characters to replace while staying within the limit of k changes.

Character Replacement with Uppercase English Char

Explanation : Either replace the ‘X’s with ‘Y’s, or replace the ‘Y’s with ‘X’s.

Constraints:

  • 1 <= s.length <= 1000
  • 0 <= k <= s.length

Finding Longest Repeating Character Replacement Solution

Recommendation for Time and Space Complexity – You should aim for a solution with O(n) time and O(m) space, where n is the length of the given string and m is the number of unique characters in the string.

Hints for solving problems

Hint 1 :

Which characters would you replace in a string to make all its characters unique? Can you think with respect to the frequency of the characters?

 

Hint 2 :

It is always optimal to replace characters with the most frequent character in the string. Why? Because using the most frequent character minimizes the number of replacements required to make all characters in the string identical. How can you find the number of replacements now?

There are mainly 3 approach to solve this problem-

  1. Brute Force Method
  2. Sliding Window Method
  3. Sliding Window Mehtod(Optimal)

1. Brute Force Method

Generate all possible substrings and check how many replacements are needed for each. Track the longest substring where replacements do not exceed the allowed limit.

  • Time complexity: O(n^2)
  • Space complexity: O(m)

where n is the length of the string and m is the total number of unique characters in the string.

Code

2. Sliding Window Method

Maintain a sliding window and expand it to include more characters. If the number of characters to replace exceeds the limit, shrink the window from the left. Track the longest valid window during this process.

  • Time complexity: O(m*n)
  • Space complexity: O(m)

where n is the length of the string and m is the total number of unique characters in the string.

Code

3. Sliding Window Method(Optimal)

Track the frequency of characters within the sliding window. If the window size minus the count of the most frequent character exceeds the allowed replacements, adjust the window size. This method ensures efficient computation by focusing on the most frequent character and minimizing unnecessary replacements.

  • Time complexity: O(n)
  • Space complexity: O(m)

where n is the length of the string and m is the total number of unique characters in the string.

Code

More Articles