Longest Repeating Character Replacement
The problem
Given an integer k and a string s, any character in the string can be selected and changed to any other uppercase English character. This operation can be performed up to** k **times. After completing these steps, return the length of the longest substring that contains the same letter.
Input : s = "BAABAABBBAAA" , k = 2 Output : 6 Explanation : we can change the B present at index 0 , 3 (0 base indexing) to A. The new string is "AAAAAABBBAAA". The substring "AAAAAA" is the longest substring having same letter with length 6.
Input : s = "AABABBA" , k = 1 Output : 4 Explanation : The underlined characters are changed in the new string obtained. The new string is "AABBBBA". The substring "BBBB" is the answer. There are other ways to achieve this answer.
Input : s = "ABCDEF" k = 1
- 1 <= s.length <= 105
- 0 <= k <= s.length
- s contains only English uppercase letters.
cpp
class Solution {
public:
int characterReplacement(string s, int k) {
//your code goes here
}
};java
class Solution {
public int characterReplacement(String s, int k) {
//your code goes here
}
}python
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
#your code goes herejavascript
class Solution {
characterReplacement(s, k) {
//your code goes here
}
}csharp
public class Solution
{
public int CharacterReplacement(string s, int k)
{
//your code goes here
}
}go
func characterReplacement(s string, k int) int {
}Stuck? Show a way to structure it+
- 01Expand the right boundary and update its frequency.
- 02Track the highest frequency seen in the window.
- 03Shrink while window length minus that frequency exceeds k.
- 04Record the maximum valid length.
- 05Use a fixed alphabet count array.
Reference answer
Then expect these follow-ups
Why is a stale maxFreq still correct here?
Tests: correctness reasoning
How would this change for an arbitrary Unicode alphabet?
Tests: implementation extension
Hiring now
Software engineer roles are open right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Senior Software Engineer -.NET
Tyler Technologies · Annapolis, Maryland

Software Development Engineer II
SaaS Labs · Bengaluru, Karnataka, India

Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)
Metropolitan Transportation Authority · New York, NY
Next question