Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Replace at most k characters so that the longest possible substring consists of one repeated letter; return its length.

Problem: Replace at most k characters so that the longest possible substring consists of one repeated letter; return its length.
def longest(s, k):
    cnt, l, top, best = {}, 0, 0, 0
    for r, c in enumerate(s):
        cnt[c] = cnt.get(c, 0) + 1; top = max(top, cnt[c])
        if r - l + 1 - top > k:
            cnt[s[l]] -= 1; l += 1
        best = max(best, r - l + 1)
    return best
print(longest("ABBBACCBA", 2))
What is printed?
  1. A. 6
  2. B. 5
  3. C. 7
  4. D. 4

Correct answer: B. 5

The window is valid while (length − count of its most frequent letter) ≤ k. 'ABBBA' needs only its two A's changed, giving 5; every window of length 6 contains at most 3 copies of any letter, so it would need 3 changes. top is never decreased, which only delays shrinking and never inflates the answer.

More Coding Interview Problems questions

Exams that ask this topic