424. Longest Repeating Character Replacement
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Sliding Window
- Time
- O(n)
- Space
- O(1)
Standard Solution (C++)
SummaryFind the longest substring you can make consist of one repeated character, given at most k allowed replacements of other characters.
Approach
Slide a window while tracking the count of the most frequent character inside it.
- Expand the right edge and update letter counts plus the running max count.
- The window is valid when (window size minus max count) is at most k; otherwise shrink from the left.
- The answer is the largest valid window seen.
class Solution {
public:
int characterReplacement(string s, int k) {
int count[26] = {0};
int left = 0, maxCount = 0, best = 0;
for (int right = 0; right < (int)s.size(); ++right) {
maxCount = max(maxCount, ++count[s[right] - 'A']);
while ((right - left + 1) - maxCount > k) {
count[s[left] - 'A']--;
left++;
}
best = max(best, right - left + 1);
}
return best;
}
}; Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.