Longest Repeating Character Replacement - Problem

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations.

Input & Output

Example 1 — Basic Case
$ Input: s = "ABAB", k = 2
Output: 4
💡 Note: Replace the 2 'B's with 'A's (or 2 'A's with 'B's) to get "AAAA" or "BBBB". Maximum length is 4.
Example 2 — Limited Replacements
$ Input: s = "AABABBA", k = 1
Output: 4
💡 Note: Replace one 'B' to get "AABAAAA" or similar. The longest substring of same characters is 4.
Example 3 — All Same Characters
$ Input: s = "AAAA", k = 2
Output: 4
💡 Note: All characters are already the same, so no replacements needed. Length is 4.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only uppercase English letters
  • 0 ≤ k ≤ s.length

Visualization

Tap to expand
Longest Repeating Character ReplacementInput: s = "ABAB", k = 2ABABReplace 2 charactersAAAAOutput: Maximum Length = 4
Understanding the Visualization
1
Input
String "ABAB" with k=2 replacements allowed
2
Process
Find longest substring that can be made uniform
3
Output
Maximum length achievable is 4
Key Takeaway
🎯 Key Insight: Use sliding window - a window is valid when window_length - max_frequency ≤ k
Asked in
Microsoft 45 Amazon 38 Google 32 Facebook 28
125.0K Views
High Frequency
~25 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen