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 Replacement INPUT String s: A B A B 0 1 2 3 Input Values: s = "ABAB" k = 2 Sliding Window Concept: Window expands/shrinks Max k=2 changes allowed in any window ALGORITHM STEPS 1 Initialize Window left=0, right=0, maxCount=0 2 Expand Right Add char, update frequency 3 Check Validity windowLen - maxFreq <= k 4 Shrink if Invalid Move left pointer right Frequency Count Table: Char Count A: 2 B: 2 maxLen = max(maxLen, right - left + 1) FINAL RESULT Optimal Window Found: A A A A B-->A B-->A Output: 4 OK - Verified! Length 4, k=2 used Changed 2 B's to A's All 4 chars now same Key Insight: The sliding window is valid when (window_length - max_frequency_char) <= k. This means we only need to change the non-dominant characters. Track the most frequent character in current window. Time: O(n), Space: O(26) = O(1) for uppercase letters. TutorialsPoint - Longest Repeating Character Replacement | Optimal Solution (Sliding Window)
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