Back to Dashboard

Longest Substring with Same Letters after Replacement

Hard

Problem Statement

Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement.

Examples

Example 1:

  • Input: str="aabccbb", k=2
  • Output: 5

Approach 1 Sliding Window:

 class Solution {
    //find the max repeating char in a window and count the length of others and if it's > k reduce window
    public int characterReplacement(String s, int k) {
        var charCountMap = new HashMap<Character, Integer>();
        int windowStart = 0, maxRepeatingChar = 0, maxLength = 0;
        for (int windowEnd = 0; windowEnd < s.length(); windowEnd ++) {
            var ch = s.charAt(windowEnd);
            charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
            maxRepeatingChar = Math.max(maxRepeatingChar, charCountMap.get(ch));
            while (windowEnd - windowStart + 1 - maxRepeatingChar > k) {
                var startCh = s.charAt(windowStart);
                charCountMap.put(startCh, charCountMap.get(startCh) - 1);
                if (charCountMap.get(startCh) == 0) {
                    charCountMap.remove(startCh);
                }
                windowStart ++;
            }
            maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
        }
        return maxLength;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

ArraySliding Window

Date

2026-02-14
View Problem Source