Problem Statement

You are given:

You can perform at most k operations. In each operation, you can change any character of the string to any other uppercase English letter.

Goal: Find the length of the longest substring that can be transformed into a string with all identical characters after performing at most k changes.

Examples

Example 1

Input: s = "ABBA", k = 2
Output: 4

Explanation: Change both 'A' to 'B' → "BBBB". Max substring length = 4

Example 2

Input: s = "ADBD", k = 1
Output: 3

Explanation: Change 'B' to 'D' → "ADDD". Max substring length = 3

Understanding the Problem

We want the longest substring where most characters are the same, and at most k characters need to be replaced to make all characters identical.

Key Observation:

changes_needed = window_size - maxCount

Approach: Sliding Window

Implementation in C#

public class Solution
{
    public int longestSubstr(string s, int k)
    {
        int[] count = new int[26]; // Frequency array for 'A'-'Z'
        int maxCount = 0;           // Max frequency in current window
        int left = 0, maxLength = 0;

        for (int right = 0; right < s.Length; right++)
        {
            count[s[right] - 'A']++;
            maxCount = Math.Max(maxCount, count[s[right] - 'A']);

            // If more than k changes needed, shrink window
            while ((right - left + 1) - maxCount > k)
            {
                count[s[left] - 'A']--;
                left++;
            }

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

        return maxLength;
    }
}

Step-by-Step Example: "ABBA", k = 2

Output: 4

Explanation: Change both 'A' to 'B' → "BBBB".

Complexity Analysis

Conclusion

The sliding window technique combined with a frequency array allows us to efficiently find the longest substring that can be transformed into all identical characters.

This method works even for large strings up to 10^5 characters.