Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the length of the longest substring that can be turned into a single repeated letter by changing at most k characters.

Problem: Find the length of the longest substring that can be turned into a single repeated letter by changing at most k characters.
def longest_rep(s, k):
    cnt = [0] * 26
    l = maxf = best = 0
    for r, ch in enumerate(s):
        cnt[ord(ch) - 65] += 1
        maxf = max(maxf, cnt[ord(ch) - 65])
        while r - l + 1 - maxf > k:
            cnt[ord(s[l]) - 65] -= 1
            l += 1
        best = max(best, r - l + 1)
    return best
print(longest_rep("AABABBA", 1), longest_rep("ABCDE", 2))
What is printed?
  1. A. 5 3
  2. B. 4 2
  3. C. 3 3
  4. D. 4 3

Correct answer: D. 4 3

A window is fixable if its length minus the count of its most frequent letter is ≤ k. "AABABBA" with k = 1 gives "AABA" or "ABBB"-style windows of length 4; "ABCDE" with k = 2 gives any 3 letters. maxf never decreases, which is safe because only a larger maxf can produce a longer answer. O(26 + n).

More Coding Interview Problems questions

Exams that ask this topic