Friday, January 22, 2021

Longest Repeating Character Replacement

Problem: Given a string s that consists of only uppercase English letters, you can perform at most k operations on that string. In one operation, you can choose any character of the string and change it to any other uppercase English character.

Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.

Example:

Input:
s = "AABAB", k = 1

Output:
4

Explanation:
Replace the first 'B' with 'A' and form "AAAAB". The substring "AAAA" has the longest repeating letters, whose length is 4.


Approach: We can use sliding window approach here. The window size here would be the frequency of the character occurred maximum time plus number of  operations we can do. Right that will be the longest repeating letters substring.


Implementation in C#:

        public int CharacterReplacement(string s, int k)

        {

            int maxCount = 0;

            int[] count = new int[26];

            int result = 0;

            for (int begin = 0, end = 0; end < s.Length; ++end)

            {

                maxCount = Math.Max(maxCount, ++count[s[end] - 'A']);

                if (end - begin + 1 > k + maxCount)

                {

                    --count[s[begin++] - 'A'];

                }

                result = Math.Max(result, end - begin + 1);

            }

            return result;

        }


Complexity: O(n)

No comments:

Post a Comment