
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <string.h>
int characterReplacement(char* s, int k) {
int freq[26] = {0};
int left = 0, right = 0;
int maxCount = 0, maxLen = 0;
int len = strlen(s);
for (; right < len; right++) {
freq[s[right] - 'A']++;
if (freq[s[right] - 'A'] > maxCount) {
maxCount = freq[s[right] - 'A'];
}
while ((right - left + 1) - maxCount > k) {
freq[s[left] - 'A']--;
left++;
}
if ((right - left + 1) > maxLen) {
maxLen = right - left + 1;
}
}
return maxLen;
}
int main() {
char s[] = "AABABBA";
int k = 1;
int result = characterReplacement(s, k);
printf("%d\n", result); // 4
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(n) | The sliding window expands and contracts across the entire string exactly once. Each character is processed at most twice — once when expanding the window and once when shrinking it — making the overall time linear. |
| Average Case | O(n) | In a typical scenario, the window slides through the string while maintaining frequency counts. Each character is added and removed from the window at most once, resulting in linear time complexity. |
| Worst Case | O(n) | Even in the worst case, where the window frequently contracts due to exceeding the allowed replacement count, the left and right pointers move from start to end only once. This gives a linear time complexity. |