Find longest uniform substring after k replacements
Company: Apple
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates skills in string processing, frequency analysis, and algorithmic optimization within the Coding & Algorithms domain, focusing on practical application of linear-time, constant-space techniques.
Constraints
- 1 <= |s| <= 2 * 10^5 (s may also be empty)
- s consists of ASCII characters
- 0 <= k <= |s|
- Required time complexity: O(n)
- Required space complexity: O(1) amortized (alphabet size treated as constant)
Examples
Input: ("AABABBA", 1)
Expected Output: 4
Explanation: Replace one character to get a run of 4 identical chars (e.g. AABABBA -> AAAA-window over 'AABA' or 'ABBA' yields length 4).
Input: ("aaabbc", 2)
Expected Output: 5
Explanation: Window 'aaabb' (length 5): replace the two 'b's with 'a' using k=2 replacements.
Input: ("abcd", 1)
Expected Output: 2
Explanation: All distinct, so any length-2 window needs exactly 1 replacement; length 3 would need 2 > k.
Input: ("", 0)
Expected Output: 0
Explanation: Empty string has no substring; answer is 0.
Input: ("AAAA", 0)
Expected Output: 4
Explanation: Already uniform; no replacements needed, whole string qualifies.
Input: ("ABAB", 2)
Expected Output: 4
Explanation: Replace the two 'B's (or two 'A's) using k=2 to make the whole string uniform.
Input: ("A", 0)
Expected Output: 1
Explanation: Single character is trivially uniform.
Input: ("ABCDE", 0)
Expected Output: 1
Explanation: All distinct with no replacements allowed; only single characters are uniform.
Input: ("AABABBA", 0)
Expected Output: 2
Explanation: With k=0, the longest existing run of one character is the 'BB' (or 'AA'), length 2.
Hints
- Slide a window over s and keep a count of each character inside it.
- Track the highest single-character frequency in the window (maxFreq). The cost to make the window uniform is windowLength - maxFreq; the window is valid when that cost is <= k.
- When the window becomes invalid, advance the left pointer. You never need to decrease maxFreq when shrinking — a stale maxFreq only makes the validity test stricter, never looser, so it cannot overcount.