1. All Substrings Frequency Evaluation
Intuition
For each start index i from 0 to N - 1: maintain a 26-count array. For each end index j from i to N - 1: increment count of s[j], find maxFreq among all 26 counts. If (j - i + 1) - maxFreq <= k, update maxLen = max(maxLen, j - i + 1).
When to apply: Basic baseline comparison.
Algorithm
- Initialize
maxLen = 0. - For
ifrom 0 ton - 1: -
count = [0] * 26,maxFreq = 0. - For
jfromiton - 1: -
count[s[j] - 'A']++. -
maxFreq = max(maxFreq, count[s[j] - 'A']). - If
(j - i + 1) - maxFreq <= k:maxLen = max(maxLen, j - i + 1). - Return
maxLen.
All Substrings Frequency Evaluation
2 of 2 questions left todayObservation: Inspect candidate window s[0
Observation: Inspect candidate window s[0..2] = 'AAB' of length 3.
Decision: Dominant character is 'A' with count 2. Replacements needed = 3 - 2 = 1 <= k (1). Valid window; update maxLen = 3.
Invariant: A substring can be transformed into repeating characters if len - maxFreq <= k.
#include <iostream>#include <string>#include <vector>#include <algorithm> class Solution {public: int characterReplacement(std::string s, int k) { int n = s.size(), maxLen = 0; for (int i = 0; i < n; ++i) { int count[26] = {0}; int maxFreq = 0; for (int j = i; j < n; ++j) { count[s[j] - 'A']++; maxFreq = std::max(maxFreq, count[s[j] - 'A']); if ((j - i + 1) - maxFreq <= k) { maxLen = std::max(maxLen, j - i + 1); } } } return maxLen; }}; int main() { Solution sol; std::cout << sol.characterReplacement("ABAB", 2) << std::endl; // 4 std::cout << sol.characterReplacement("AABABBA", 1) << std::endl; // 4 return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— N2 substrings evaluated in constant operations. - Space complexity:
O(1)
Why Brute Force Doesn't Scale:
Non-shrinking window in strict single-pass O(N).
26-integer stack array.